Jun 04

I program with different languages and for a while now I have wanted to make the K&R variant coding style my default in Visual Studio.

So what do I mean by the K&R variant coding style, this coding style was named after co authors of the book The C Programming Language (thank you Wikipedia!) Kernighan and Ritchie. The variant I like is based on Java – rather than taking up a new line I like the opening brace on the first line of the statement block.

K&R variant coding style example:

public class Class1 {
    public Class1() {

    }

    public string Method1() {
        return "Method1";
    }
}

Visual Studio default (Allman coding style):

public class Class1
{
	public Class1()
    {
       
	}

    public string Method1()
    {
        return "Method1";
    }
}

I was put off using the K&R variant coding style when using C# because the default in Visual Studio is the Allman coding style. However after recently downloading the MVC 2.0 RTM source I noticed that the project uses the K&R variant coding style.

ChildActionOnlyAttribute snippet from the MVC 2.0 source code:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public class ChildActionCacheAttribute : ActionFilterAttribute {

        private const string _cacheKeyPrefix = "__MVC_ChildActionCache_Entry_";
        private static readonly object _typeId = new object();
        private readonly object _itemsCacheKey = new object();
        private string _key;

        public int Duration {
            get;
            set;
        }
        
        public string Key {
            get {
                return _key ?? String.Empty;
            }
            set {
                _key = value;
            }
        }
    }

Knowing that a very popular C# project uses the K&R variant coding style I decided to change my default coding style in Visual Studio. Below is a basic screencast I created that shows you how to change the default coding style to the K&R variant in Visual Studio 2010. BTW the settings are in exactly the same place in Visual Studio 2008.

A quick Google search found that I’m not alone in my thinking http://scyanide.com/2010/02/xcode-the-starting-curly-brace/.

7 Responses to “Visual Studio 2010 – K&R Coding Style Variant”

  1. serejko says:

    Is there a way to do the same thing for C++?

  2. kyorry says:

    hi, could you send me the video via email, because i can’t open all the YouTube videos, thanks

  3. Xiang says:

    Hi, I could not find the “new line” option for C++, which exists for C#… Could you please show me how to configure it for C++? Thanks.

  4. […] problemu, którego nie do końca potrafiłem nazwać natknąłem się na tę oto stronę Visual Studio 2010 – K&R Coding Style Variant. Okazuje się, że styl pisania kodu ma nawet swoją nazwę! I tak jak to jest opisane w artykule […]

Leave a Reply to DalSoft

preload preload preload