Share via


A Brief History Of C# Style

A number of astute developers have noted that the C# code style enforced by Microsoft StyleCop differs in some ways from the style typically seen in sample code coming from the Microsoft Developer Division. For example, the very fine book Framework Design Guidelines by Krzysztof Cwalina and Brad Abrams includes many code samples which use a different style, and this style is briefly described in an appendix in the back of the book.

In fact, the differences between the "StyleCop style" and the "Framework Design Guidelines style" are relatively minor. One of the biggest differences is that the framework style prefixes private and internal fields with an underscore, while StyleCop style omits the underscore and instead prefixes all class members with this.

The reason for the differences between the two styles is largely historical. The team that developed the first version of the .Net CLR consisted almost entirely of C++ developers. Remember, at this time no-one had ever heard of C# and in fact the language only existed on paper. When the original CLR was stable enough for internal use, people from the CLR team began writing test and sample code in the new C# language, mainly to test the CLR itself. Being C++ developers, these people naturally wrote their first C# code in a style that very much resembled C++, with liberal use of the m_ prefix, very little whitespace or comments, short, cryptic variable names, lots of Hungarian notation, etc.

Soon after this, an offshoot of the CLR team began writing the first version of the .Net Framework. Most of this code was written in C#. This was the first production C# code written anywhere in the world! Again, the team chose a coding style that mostly resembled C++. Over time this style has changed slightly, but the Framework team still uses this style for its internal C# code, as well as sample C# code provided to customers and partners.

After the first version of the .Net Framework was released, many other teams within Microsoft began writing new code in C#. Some of the biggest early adopters were, naturally, the Office team and the Windows team. Within a couple of years, almost every product group at Microsoft was writing at least some percentage of its code in C#. The architects and managers in these teams (being architects and managers) each took the time to come up with their own, individual style guidelines for the new C# language. In some places these style guidelines differed wildly according to the whims and fancies of the leaders of these teams. However, over time some C# style trends began to form, and these trends did not always follow the original style used by the Framework team. C# style had begun to evolve.

A short time after this, a brilliant young developer at Microsoft (ok, it was me) decided to take it upon himself to write a little tool which could detect variances from the C# style used within his team. StyleCop was born. Over the next few years, we gathered up all of the C# style guidelines we could find from the various teams within Microsoft, and picked out all of best practices which were common to these styles. These formed the first set of StyleCop rules. One of the earliest rules that came out of this effort was the use of the this prefix to call out class members, and the removal of any underscore prefixes from field names. C# style had officially grown apart from its old C++ tribe.

Development on StyleCop continued on and off for the next five or six years, and over this time many new rules were introduced. As you might expect, many wars were fought over the nature of these rules, and much blood was shed. In the end, decisions about StyleCop rules always came down to the following:

  1. What are most teams doing already?
  2. Which option is the most readable (highly subjective)?
  3. Which option will be the easiest to maintain over time?

StyleCop rules tend to encourage whitespace and openness in the code, as well as lots of comments and documentation. The rules also encourage developers to be explicit about what they are doing, and to minimize the need for assumption or guesswork on the part of the reader.

Today, StyleCop is very widely used within Microsoft, although it is still not an official, mandated tool internally. The .Net Framework team still writes code and samples using the original style derived from C++, and there are still some teams that have chosen to go their own way (and still some architects and managers with big egos). However, that is happening less and less internally, as more and more teams adopt the tool.

Now we have continued the evolution by releasing StyleCop to the world!

Thanks.

Comments

  • Anonymous
    May 25, 2008
    I am grateful that Microsoft has released this tool, however, I am not grateful that, in it's default configuration, it promulgates overuse of "this."  I haven't been able to find a good justification for this, I haven't come across any C# books advocating this style, and I personally believe that adding "this." everywhere clutters the code and is unnecessary. After all, we all by now know that we are writing classes, and that classes have fields, properties, and methods that are in scope without derefencing an object reference or pointer.  By insisting that "this." prefix all these references, it is a step backwards towards C style (pre classes).

  • Anonymous
    May 25, 2008
    Thanks for the background - I wasn't aware this was an 'on-going battle' within Microsoft. Btw the tool is really awesome and will definitely become part of our process.

  • Anonymous
    May 25, 2008
    Thanks for the brief recap, which confirms what I've often heard out of softies over the years. Sadly, it also confirms the exact moment I stopped paying attention to many MSFT coding guidelines, that being the moment when the "this." craze took a single character discriminator and turned it into a five character source of density-increasing noise that offers zero increased utility over a single underscore. For lack of a better way of phrasing it on this muggy morning: epic fail.

  • Anonymous
    May 25, 2008
    It's interesting that ReSharper discourages superfluous use of the this reference while StyleCop encourages it. The MSIL generated by the C# compiler is the same in both cases so one can't argue that it's much more than a style choice. Personally, I like using the this reference to make it perfectly clear to new readers of the code. Then again, the m_ prefix has the same effect. And it's arguable that the s_ prefix for static members fields used by some C++ shops is even more descriptive. All in all, having a standard and enforcing it is what's important.

  • Anonymous
    May 25, 2008
    Could we expect a source analysis for VB .Net ?

  • Anonymous
    May 26, 2008
    > All in all, having a standard and enforcing it is what's important. ... and that is why it is important to be able to write seamlessly custom rules. This 'this.' debate underline the fact that not everybody wish to have the same rule. With NDepend, enforcing the m_ and s_ prefix is as easy as writing these 2 conventions: WARN IF Count > 0 IN SELECT FIELDS WHERE !NameLike "^s_" AND IsStatic WARN IF Count > 0 IN SELECT FIELDS WHERE !NameLike "^m_" AND !IsStatic

  • Anonymous
    May 26, 2008
    In my own code, I'm pretty big on using "m_" and "s_". I tried to use "this" for a while, but I would usually forget to type it. Now that I have this tool to play with, I think I'll give it another go.

  • Anonymous
    May 27, 2008
    Are "this", "", "m" and "s_" only about explicitly repeating the scope of the variable? I realize it's a preference thing, but I'm curious about why people prefer it.

  • Anonymous
    May 27, 2008
    "I realize it's a preference thing, but I'm curious about why people prefer it." It takes about 2 seconds to determine the scope of a variable used in a method without the 'm_'. With it, it's instantaneous.

  • Anonymous
    May 27, 2008
    The comment has been removed

  • Anonymous
    May 28, 2008
    I find it ironic that Microsoft, on the one hand discourages the use of prefixes to denote class members (e.g., '', "m", etc.) but then advocates "this." as a prefix.  How is "this." any different than "m_"?

  • Anonymous
    May 28, 2008
    Why StyleCop is suggesting to put using statement under the namespace block? Is that just a style to write or it has some differences? If the difference is just to make using statements available for that namespace and class with-in only then I am not convinced to use this style because the another suggestion says that we should have only one class in a file. So what is the catch here?

  • Anonymous
    May 29, 2008
    The comment has been removed

  • Anonymous
    May 30, 2008
    .NET A Brief History Of C# Style Writing your own rules for Microsoft Source Analysis for C# Checking

  • Anonymous
    May 31, 2008
    I tend to use the underscore (_name) to indicate that its a backing variable for a property, while a private or local variable would just start with lower case (name). Its meant to communicate the fact that you  should not use _name to except through the property.

  • Anonymous
    June 02, 2008
    My learned colleague Howard van Rooijen recently blogged about the new release of Microsoft Source Analysis

  • Anonymous
    June 05, 2008
    The comment has been removed

  • Anonymous
    June 06, 2008
    I'll ask too, any chance for this to come out for VB????

  • Anonymous
    June 09, 2008
    As several comments here have indicated, style is a matter of preference. While I agree that a given Development organization needs to have a single set of style preferences enforced, I'm afraid I can't agree on having the Microsoft style preferences enforced on my organization. The lack of configurability makes this tool a non-starter for us. John

  • Anonymous
    June 19, 2008
    Since it is agreed that a prefix to distinguish scope is needed why not save yourself typing and reading and use the shortest? "this." is too much trouble. "m_" underscode will lead to carpal syndrome. just use "m"! and I'm not a C++ programmer :)

  • Anonymous
    July 01, 2008
    Where can I find StyleCop rules? If I had one, I can give it to my developers so that they can code accordingly. I know there will be slippages and there comes StyleCop handy. Thanks for the wonderful tool. Kishore

  • Anonymous
    July 01, 2008
    > Are "this", "", "m" and "s_" only about explicitly repeating the scope of the variable? Because the compiler won't give any messages on FuncA: class A {      private int a = 0;      public A()      {            a = 3;      }      public int Value      {            get { return a; }            set { a = value; }      }      public int Func(int a)      {            return a*a;      } }

  • Anonymous
    July 01, 2008
    It will be good to know to which extend this tool in its style rules has official support in Microsoft, and if will see them widely adopted in the source code shown by Microsoft in the future. If this is not the case, I think maybe it is not worth investing to adopt rules that break what we use to see in the code found in internet inside and outside Microsoft.

  • Anonymous
    July 05, 2008
    "I tend to use the underscore (_name) to indicate that its a backing variable for a property, while a private or local variable would just start with lower case (name). Its meant to communicate the fact that you  should not use _name to except through the property." Haha i do exactly the same! And here i was thinking i had an original idea... I used to do this. all the time, just for the intellisense. But since i got resharper i don't bother anymore.

  • Anonymous
    July 10, 2008
    This tool is SO cool.. but most of our projects are web projects. Any ideas on making it work for those? Or suggestions for an alternate tool....??

  • Anonymous
    July 11, 2008
    Hi Dennis C. The tool should already support web projects. There were a couple of problems around this which will be fixed in 4.3. Perhaps you are hitting that?

  • Anonymous
    July 11, 2008
    When can we expect better documentation of the rules? The lack of documentation is the #1 problem with the project right now for me.

  • Anonymous
    July 15, 2008
    Yes, it's one of those posts where you either agree or disagree completely :) Anyway, after having

  • Anonymous
    July 15, 2008
    Yes, it's one of those posts where you either agree or disagree completely :) Anyway, after having

  • Anonymous
    July 19, 2008
    Ah yes, lets start the debate of where to put the curly brackets and where to put spaces... Lo and behold, you know I could use a tool like resharper and automatically reformat the code to how I like to see it... WOW... I use resharper and have to say its rules are actually very very good. They are both logical and not bothersome. They worry about things that need to be worried about. Maybe Microsoft should learn from Reshaper a bit?

  • Anonymous
    August 06, 2008
    It sounds like this could be a useful tool, but more useful would be a set of industry-wide guidelines on coding-style. The difficulty is how to decide who wins on debates like m_, s_ and "this.". There could take the form of an open forum, with discussions (like the one above) on contentious issues, and voting for the top options, with everyone agreeing to go for the democratically chosen choice, or at least having the democratic choice being a named-standard (e.g. The StyleCop Way). People can learn it, and either follow it, or know where they are differing. Just my 2 cents!

  • Anonymous
    September 18, 2008
    Why is each developer looking at the same text? Something that lets me see it my way, and lets you see it your way is what we really need. Semantics, of course, should be preserved, and these should be subject to more important static analysis tools.

  • Anonymous
    September 27, 2008
    The comment has been removed

  • Anonymous
    October 13, 2008
    Please use the StyleCop Discussion Forum for further comments as it provides a better mechanism for tracking topics and follow-ups.