Internal Coding Guidelines



Table of Contents

1. Introduction………………………………………………………………………………………………………………………… 1

2. Style Guidelines…………………………………………………………………………………………………………………… 2

2.1 Tabs & Indenting……………………………………………………………………………………………………………….. 2

2.2 Bracing…………………………………………………………………………………………………………………………….. 2

2.3 Commenting………………………………………………………………………………………………………………………. 2

2.3.1 Documentation Comments………………………………………………………………………………………………. 2

2.3.2 Comment Style…………………………………………………………………………………………………………….. 3

2.4 Spacing…………………………………………………………………………………………………………………………….. 3

2.5 Naming…………………………………………………………………………………………………………………………….. 4

2.6 Naming Conventions……………………………………………………………………………………………………………. 4

2.6.1 Interop Classes…………………………………………………………………………………………………………….. 4

2.7 File Organization………………………………………………………………………………………………………………… 5

 

1. Introduction

First, read the .NET Framework Design Guidelines. Almost all naming conventions, casing rules, etc., are spelled out in this document. Unlike the Design Guidelines document, you should treat this document as a set of suggested guidelines.  These generally do not effect the customer view so they are not required.   

2. Style Guidelines

2.1 Tabs & Indenting

Tab characters (\0x09) should not be used in code. All indentation should be done with 4 space characters.

2.2 Bracing

Open braces should always be at the beginning of the line after the statement that begins the block. Contents of the brace should be indented by 4 spaces. For example:

if (someExpression)
{
   DoSomething();
}
else
{
   DoSomethingElse();
}

“case” statements should be indented from the switch statement like this:

switch (someExpression)
{

   case 0:
      DoSomething();
      break;

   case 1:
      DoSomethingElse();
      break;

   case 2:
      {
         int n = 1;
         DoAnotherThing(n);
      }
      break;
}

Braces should never be considered optional. Even for single statement blocks, you should always use braces. This increases code readability and maintainability.

for (int i=0; i<100; i++) { DoSomething(i); }

2.3 Single line statements

Single line statements can have braces that begin and end on the same line.

public class Foo
{
   int bar;

   public int Bar
   {
      get { return bar; }
      set { bar = value; }
   }

}

It is suggested that all control structures (if, while, for, etc.) use braces, but it is not required.

2.4 Commenting

Comments should be used to describe intention, algorithmic overview, and/or logical flow.  It would be ideal, if from reading the comments alone, someone other than the author could understand a function’s intended behavior and general operation. While there are no minimum comment requirements and certainly some very small routines need no commenting at all, it is hoped that most routines will have comments reflecting the programmer’s intent and approach.

2.4.1 Copyright notice

Each file should start with a copyright notice. To avoid errors in doc comment builds, you don’t want to use triple-slash doc comments, but using XML makes the comments easy to replace in the future. Final text will vary by product (you should contact legal for the exact text), but should be similar to:

//———————————————————————–
// <copyright file=”ContainerControl.cs” company=”Microsoft”>
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//———————————————————————–

2.4.2 Documentation Comments

All methods should use XML doc comments. For internal dev comments, the <devdoc> tag should be used.

public class Foo
{

/// <summary>Public stuff about the method</summary>
/// <param name=”bar”>What a neat parameter!</param>
/// <devdoc>Cool internal stuff!</devdoc>
///
public void MyMethod(int bar) { … }

}

However, it is common that you would want to move the XML documentation to an external file – for that, use the <include> tag.

public class Foo
{

   /// <include file=’doc\Foo.uex’ path=’docs/doc[@for=”Foo.MyMethod”]/*’ />
   ///
   public void MyMethod(int bar) { … }

}

UNDONE§ there is a big doc with all the comment tags we should be using… where is that?

2.4.3 Comment Style

The // (two slashes) style of comment tags should be used in most situations. Where ever possible, place comments above the code instead of beside it.  Here are some examples:

// This is required for WebClient to work through the proxy
GlobalProxySelection.Select = new WebProxy(“http://itgproxy”);

// Create object to access Internet resources
//
WebClient myClient = new WebClient();

Comments can be placed at the end of a line when space allows:

public class SomethingUseful
{
    private int          itemHash;            // instance member
    private static bool  hasDoneSomething;    // static member
}

2.5 Spacing

Spaces improve readability by decreasing code density. Here are some guidelines for the use of space characters within code:

  • Do use a single space after a comma between function arguments.
    Right:          Console.In.Read(myChar, 0, 1);
    Wrong:       Console.In.Read(myChar,0,1); 
  • Do not use a space after the parenthesis and function arguments
    Right:          CreateFoo(myChar, 0, 1)
    Wrong:       CreateFoo( myChar, 0, 1 )
  • Do not use spaces between a function name and parenthesis.
    Right:          CreateFoo()
    Wrong:       CreateFoo ()
  • Do not use spaces inside brackets.
    Right:    x = dataArray[index];
    Wrong:       x = dataArray[ index ];
  • Do use a single space before flow control statements
    Right:          while (x == y)
    Wrong:       while(x==y)
  • Do use a single space before and after comparison operators
    Right:          if (x == y)
    Wrong:       if (x==y)

2.6 Naming

Follow all .NET Framework Design Guidelines for both internal and external members. Highlights of these include:

  • Do not use Hungarian notation
  • Do not use a prefix for member variables (_, m_, s_, etc.). If you want to distinguish between local and member variables you should use “this.” in C# and “Me.” in VB.NET.
  • Do use camelCasing for member variables
  • Do use camelCasing for parameters
  • Do use camelCasing for local variables
  • Do use PascalCasing for function, property, event, and class names
  • Do prefix interfaces names with “I”
  • Do not prefix enums, classes, or delegates with any letter

The reasons to extend the public rules (no Hungarian, no prefix for member variables, etc.) is to produce a consistent source code appearance. In addition a goal is to have clean readable source. Code legibility should be a primary goal.

2.7 Naming Conventions

2.7.1 Interop Classes

Classes that are there for interop wrappers (DllImport statements) should follow the naming convention below:

  • NativeMethods – No suppress unmanaged code attribute, these are methods that can be used anywhere because a stack walk will be performed.
  • UnsafeNativeMethods – Has suppress unmanaged code attribute. These methods are potentially dangerous and any caller of these methods must do a full security review to ensure that the usage is safe and protected as no stack walk will be performed.
  • SafeNativeMethods – Has suppress unmanaged code attribute. These methods are safe and can be used fairly safely and the caller isn’t needed to do full security reviews even though no stack walk will be performed.

class NativeMethods
{
   private NativeMethods() {}

   [DllImport(“user32”)]
   internal static extern void FormatHardDrive(string driveName);
}

[SuppressUnmanagedCode]
class UnsafeNativeMethods
{
   private UnsafeNativeMethods() {}

   [DllImport(“user32”)]
   internal static extern void CreateFile(string fileName);
}

[SuppressUnmanagedCode]
class SafeNativeMethods
{
   private SafeNativeMethods() {}

   [DllImport(“user32”)]
   internal static extern void MessageBox(string text);
}

All interop classes must be private, and all methods must be internal. In addition a private constructor should be provided to prevent instantiation.

2.8 File Organization

  • Source files should contain only one public type, although multiple internal classes are allowed
  • Source files should be given the name of the public class in the file
  • Directory names should follow the namespace for the class

For example, I would expect to find the public class “System.Windows.Forms.Control” in “System\Windows\Forms\Control.cs”…

  • Classes member should be alphabetized, and grouped into sections (Fields, Constructors, Properties, Events, Methods, Private interface implementations, Nested types)
  • Using statements should be inside the namespace declaration.

namespace MyNamespace
{

using System;

public class MyClass : IFoo
{

      // fields
      int foo;

      // constructors
      public MyClass() { … }

      // properties
      public int Foo { get { … } set { … } }

      // events
      public event EventHandler FooChanged { add { … } remove { … } }

      // methods
      void DoSomething() { … }
      void FindSomethind() { … }

//private interface implementations
   void IFoo.DoSomething() { DoSomething(); }

// nested types
   class NestedType { … }

}

}

Comments (142)

  1. Adarsh Bhat says:

    This is really useful. Thanks.

  2. Sam says:

    >Source files should contain only one public type

    So if I have a class Foo, and it got some enum as parameter of type Bar that is only used in Foo, shall I make a source file for Foo and one for Bar instead of putting both in one?

    If thats too confusing, an example:

    should it look like this:



    Foo.cs:

    class Foo

    {

    public enum Bar { fast, exact)

    public Foo( Bar how)

    {

    // initialize Foo according to Bar

    }

    }



    or like that:



    Bar.cs

    public enum Bar { fast, exact)

    Foo.cs:

    class Foo

    {

    public Foo( Bar how)

    {

    // initialize Foo according to Bar

    }

    }

    And what about delegates? EventArgs?

    Sam

  3. Samuel Jack says:

    There seems to be a conflict between these two guidelines:

    "Braces should never be considered optional. Even for single statement blocks, you should always use braces."

    and a few lines later

    "It is suggested that all control structures (if, while, for, etc.) use braces, but it is not required."

  4. mihailik says:

    My point on braces omitting:

    DO omit braces around simple single-statement body:

    // nice

    if( … )

    x = y+z;

    // ugly

    if( … )

    {

    x = y+z;

    }

    DO NOT omit braces around compound statements:

    // ugly

    if( … )

    foreach( … )

    x = y+z;

    // nice

    if( … )

    {

    foreach( … )

    x = y+z;

    }

    DO NOT omit braces around if-part or else-part if other part embraced:

    // ugly

    if( … )

    x = y+z;

    else

    {

    a = b+c;

    i++;

    }

    // nice

    if( … )

    {

    x = y+z;

    }

    else

    {

    a = b+c;

    i++;

    }

    This rules makes readability cleaner. IMHO.

  5. mihailik says:

    You didn’t state that. Do you really use camelCase for private constants?

  6. Kevin Westhead says:

    Sam, I think if you choose to follow the guidelines posted here then you would create two files. You would also create a separate file for each public delegate and each EventArgs-derived type. This means that if you know the full name of the public type then you can easily find the file where the source is defined.

    AppDomain is a pretty interesting example in the sscli since it exposes three EventArgs-derived types:

    AssemblyLoadEventArgs

    ResolveEventArgs

    UnhandledExceptionEventArgs

    and three delegates:

    AssemblyLoadEventHandler

    ResolveEventHandler

    UnhandledExceptionEventHandler

    The first two in each set are defined in sscliclrsrcbclsystemappdomain.cs but the last ones are defined in sscliclrsrcbclsystemunhandledexceptioneventargs.cs and sscliclrsrcbclsystemunhandledexceptioneventhandler.cs.

    Ultimately though, the important thing (as far as naming is concerned) is that each type conforms to the naming guidelines for events.

  7. Sam says:

    Thanks Kevin – so your AppDomain example does not behave like the above guidelines for public types would propose, if I understand you correctly?

    And, another thing, can I conclude that public types should not be nested? Example would be a class that throws a special exception.

    I could put the class declaration for the exception inside the class that might throw it, put then it wont be in its own source file.

    And probably nesting public types aint good anyway (I’m just searching for some reasons why to oppose to it, right now it’s just a hunch I have that nesting public types might be no good)?

  8. Stuart says:

    Are there any specific guidelines for naming gui controls? Would you use just use the type or an abbreviation of the type as a suffix?

    Label somethingLabel;

    or

    Label somethingLbl;

  9. G. Man says:

    >Source files should contain only one public type,

    I disagree with this also. It sounds good until you actually try to enforce it. If I have a class which fires some events that have their own FooEventArgs classes, I’m going to define those right there in the file. It’s stupid to create another file for those.

  10. Kevin Westhead says:

    G. Man, what happens when another class comes along that also raises an event taking a FooEventArgs, i.e. you re-use the class somewhere else? Would you split it into its own file then?

    Sam, you can read the guidelines for nested types here:

    http://msdn.microsoft.com/library/en-us/cpgenref/html/cpconusingnestedtypes.asp?frame=false

    You can also view the FxCop rule on the subject here:

    http://www.gotdotnet.com/team/fxcop/Docs/Rules/Design/NestedTypesShouldNotBeVisible.html

  11. Grim says:

    I usually break delegates/event args into matched pairs:

    ServerEvent.cs:<pre>

    public delegate void ServerEventHandler(object sender, ServerEventArgs e);

    public class ServerEventArgs : EventArgs

    {

    private IServer server;

    public ServerEventArgs(IServer server)

    {

    this.server = server;

    }

    public IServer Server {get{return this.server;}}

    }

    </pre>

    DataEvent.cs:<pre>

    public delegate void DataEventHandler(Object sender, DataEventArgs e);

    public class DataEventArgs : EventArgs

    {

    private object data = null;

    public DataEventArgs(object data)

    {

    this.data = data;

    }

    public object Data

    {

    get{return this.data;}

    }

    }

    </pre>

  12. Keith Patrick says:

    mihailik: I prefer using braces for constructs at all times for two reasons-> consistency (it’s actually easier for me to read/find them when they all look alike), and b) maintainability such that if I want to modify what my conditional does, I would rather do a carriage return and start typing than add braces, fix alignment (mine is different from the VS.Net style), then add a line. IIRC, the no braces thing came out of a desire to optimize your code to not build a scope for a single-line statement, but modern optimizing compilers should have no prob handling that.

    I’d also be interested in if there are 1 or more alignment guidelines. I find the default VS.Net one to be difficult to read when you put method params or portions of a condition on their own lines. I do a more columnar style where a change in "region" (Param list, boolean condition, etc) results in a new tab stop (using spaces of course), but I’m curious if there is a standard one that isn’t what I see on MSDN (which gives me a headache sometimes)

  13. bramster says:

    mihailik: braces around everything! It makes logic debugging much easier.

    But why not tabs for indent? To me, it helps seet of the individual blocks of code even more.

  14. Marcos says:

    Mihalik,

    It’s not just a matter of "style", insthead, those visual clues become an idiom for ourselves even when meaningless for the compiler, end even help us reduce the chances for someone in the future to introduce bugs accidentally in the code.

    For example, I disagree with that guideline in a couple of aspects, for wich I’d be even more strict:

    1) I preffer to put braces allways, even empty else parts with it own braces in ifs without else, just to avoid the risk of someone in the future having to add them and forget it or missplace them (the compiler will get rid of them).

    2) I dislike the switch sentence because it can have two different behaviors, one if every case part have a break (resembling an if… elsif… elsif), the other if some of the cases could have no break (resembling an if…. endif if… ), so I like to make it clear wich one I am using. For the former, I like to leave all the breaks righ behind te case closing brace, and for the later, leaving them in the next line and with the same indentation than the closing brace. This makes it clear wich behavior to expect from each switch in the code, before adding something inside a case later that could lead to an unwanted side effect.

  15. Brian says:

    What’s with the hating on tabs? I’ve heard this guideline before, but never understood the motivation behind it. It seems to me that tabs are ideal here, as they semantically match the notion of indentation. 4 spaces lacks that semantic meaning. And with tabs you can set the tab width in your editer.

  16. Aviator says:

    Since VB.Net doesn’t support casing, your requirements would mean the private member variable would have to be named different than the property property that exposes it.

    That’s pretty confusing. I think I’ll stick with "_myVariable".

  17. Drew Marsh says:

    Regarding 2.8, do you guys even have separate files for Enum types that are strongly tied to the class? For example, consider something like DateTime which basically "owns" the DayOfWeek enum. Do you actually have a DayOfWeek.cs for the enum or do you just include it in DateTime.cs?

  18. Robert Jeppesen says:

    Mihailik: Besides the points already posted above about always bracing (on which I agree), still another argument is that its a very common source for silly bugs, ie changing a one statement if.. into a two statement if.. and forgetting to add the braces.

  19. Kevin Westhead says:

    Drew, in the sscli there is a separate file for DayOfWeek called DayOfWeek.cs.

    If you’re interested you can get the sscli bits from http://www.microsoft.com/resources/sharedsource/default.mspx

  20. .Net Adventures says:
  21. Uwe Keim says:

    Is there a FxCop rule for your coding styles?

  22. Dale Thomas says:

    This is great stuff.

  23. Nader Soliman says:

    Also for the TABs, beside semantic meaning and the like, it is not so good to hit arrow keys four times to get to the next tab, and it is not obviously good to hit ctrl+arrow key to pass the four characters.

    So please can you give a good explanation for tabs?

    Back on the days of c/c++ on MFC, we used Hungarian notation, and m_ and it was very encourged by MS docs although being ugly and hard for developers, now it is discouraged I am happy, but I have learned to ask why? 😉

  24. Brad: what do you do with generics? Say i have a type Tuple<A>, Tuple<A,B> and Tuple<A,B,C>. They’re all public. Where do they go?

  25. Cleve Littlefield says:

    Our group doesnt allow tabs either. Why I agree about the hiting the arrow key four times argument that it is annoying, the reason is valid:

    Because you CAN set the tab width the code looks different in every editor. Especially if there are a mix of tabs and spaces, the indention can really get messed up if someone uses a different tab witdh.

    Plus I usually ignore the formating and then hit the key to have VS autoformat it or delete and retype the closing curly brace…

  26. Jørn says:

    One thing that really irritates me with one of my co-workers is that he doesn’t use spaces when concating strings.

    for example:

    querystring = "name="+Name+"&userid="+UserID+"&email="+email;

    It makes it almost impossible to read compared to:

    querystring = "name=" + Name + "&userid=" + UserID + "&email=" + email;

    Please add this rule to the .Net guidelines so I can paste it in a mail with lots of bold red text to him! 😉 I’ve tried to tell him nicely…

    Real-life example I just found:

    Write("<thead ID="RH_"+ParentEditor.ID+"_"+Row.GetPrimarykeys()+"" "+Script+" class=""+Style+"">");

  27. Well, I dont think its good idea to use 4 spaces instead of tab.It unnecessarily increase editing complexity.

  28. Dave says:

    I agree with the above, apart from:

    – I always use braces, even for wrapping single statements. This makes updating the code easier in the future.

    – I use tabs, not spaces, and standardise on 4 characters per tab.

    – I believe members should be ordered according to function; they shouldn’t be alphabetised – that’s what an editor drop-down is for.

    I wish I could get my colleague to follow the rule about spaces around operators – his code is unreadable because of this!

  29. AM says:

    "Because you CAN set the tab width the code looks different in every editor"

    So you’ll standardise on using spaces (and presumably on the number of spaces per indent), but won’t standardise on a tab setting? That’s real consistent.

  30. Jack says:

    camelCasingMakesCode less_readable_than_underscores

  31. Alex says:

    >>Well, I dont think its good idea to use 4 spaces instead of tab.It unnecessarily increase editing complexity.

    I agree tabbing is easier to manage and quicker to navigate through indentations – I’d need a really good reason to change.

    >> One thing that really irritates me with one of my co-workers is that he doesn’t use spaces when concating strings.

    I usually feel that if you concatonate more than 3 or so strings you probably would be better off using string.Format – at least for the kind of operations that you’re describing in your example (otherwise you should start considering using StringBuilder).

    Aditionally for clarity I usually bracket boolean expressions even when they don’t strictly need it; such as:

    case (20) :

    or

    foo = (x==y)? x : y ;

    or

    return (oldResult == newResult);

  32. The Internal Coding Guidelines posted by Brad Abrams are very similar to the style I prefer. Perhaps the main difference is that I use an underscore prefix for member variables, although I’ve never been completely happy with this. It does…

  33. Sam says:

    The last few posts are all about habits – you are used to work with tabs, it’ll be easier for you. You are used to spaces, they’ll be easier.

    If you are used to camelCase its easy to read, if you are used to underscores it’s easy to read, too.

    The important thing is to be consistent in the whole project. Nothings worse for readability than mixing styles.

  34. AndrewSeven says:

    "Tab characters (x09) should not be used in code. All indentation should be done with 4 space characters."

    I’m a tabs user, but it comes down to consistency and typing time. 12 spaces is a lot more keypresses than 3 tabs.

    "Using statements should be inside the namespace declaration."

    I’ve always wondered why VS.Net puts them outside in a page’s codeBehind and inside in a userControl’s codeBehind. If you stick to the one class per file rule does it really matter?

    In situation where I have several SMALL "helper" classes, like event args and handlers, for one class, I will put them in a file called "MyMainClassName Event Classes.cs".

    This filename clearly identifies a departure from the one public class/one public file rule.

    Always use braces unless its an exit condition on one line : if(guardConditionFailed) return;

    I think that if I were writing a compiler, I would always require braces.

    I tend to avoid single line compound statements like this "get { return bar; }", but I will generate code that looks like that to provide the visual cue that it is not hand written code.

    I use "_bar","bar" and "Bar" for private var,parameter name and property name.

  35. mihailik says:

    There is three different points on private fields naming:

    a) int width;

    b) int m_Width;

    c) int _Width;

    Last two conflicts with Brad’s rules. Why I use prefixes for private fields? Because of Intellisense’s case-insensitive manner.

  36. Anonymous says:

    An excellent post by Brad Abrams deta…

  37. Craig says:

    "Tab characters (x09) should not be used in code. All indentation should be done with 4 space characters."

    "I’m a tabs user, but it comes down to consistency and typing time. 12 spaces is a lot more keypresses than 3 tabs."

    Uh, you do realize you can configure the dev environment to insert spaces when you hit the Tab key, right? I use the 4 space rule, but I still only hit the tab key once for each 4 space indent.

  38. Coding standards from Microsoft – level 100

  39. From "C++ Coding Standards" by Sutter & Alexandrescu (http://www.gotw.ca/publications/c++cs.htm): 0. Don’t sweat the small stuff. (Or: Know what not to standardize.)

    Braces, spaces vs. tabs, comment style, names, etc. are all "small stuff" in the grand scheme of things.

    There are going to be very few bugs that result from using foo_bar_baz instead of fooBarBaz.

  40. enders says:

    One thing I miss is the naming convention of procedures/functions.

    They all follow verb noun.

    I prefer noun verb. Example

    You want to do something with a file. Is it

    OpenFile, GetFile, ReadFile, LoadFile

    Or

    FileOpen, FileGet, FileRead, FileLoad.

    Not convinced ? Open the Object Browser and look for words starting with get.

    I hope MS will change that

    CE

  41. A bit of reflection of my own coding style in comparison to other established coding styles at Sun, SGI, and Microsoft.

  42. A bit of reflection of my own coding style in comparison to other established coding styles at Sun, SGI, and Microsoft.

  43. Thoughts on Naming Convention

  44. Steve says:

    consistency is worth its weight in gold.

    everyone has their own style. personally I liked the old C style notation, but if I were trying to *market* a new language i’d do the same thing (say how and what to write). it makes of groups, loyal legions. formatting is stupid. with a powerful editor like they’ve produced, I seriously doubt errors will be made by using _memberName as opposed to memberName;

    CTRL+A, CTRL+KF solves most problems.

  45. I can’t believe all you smart people are arguing about tabs vs spaces, especially in terms of carat navigation.

    Are none of you aware of CTRL-Right Arrow, CTRL-Left Arrow? With ONE "keystroke" you move past all the whitespace no matter if it’s spaces or tabs.

  46. Internal Coding Guidelines (C# マイクロソフト)

  47. Joe says:

    > Do not use a prefix for member variables

    In C#, a property can differ from its backing field in case only, thus:

    public int MyProperty

    {

    get { return myProperty; }

    set { myProperty = value; }

    }

    private int myProperty;

    This is not possible in VB because of case-insensitivity. I prefer to use an underscore prefix for private fields in both C# and VB, to be consistent in both languages.

  48. Vince,

    You’re right, but the code doesn’t line up right in the editor if your tab setting is different from the author – that’s why tabs vs spaces matters.

  49. John Wood says:

    Larry,

    Absolutely right. I really don’t get where Brad is coming from here. I hope he speaks up on it at some point.

  50. Vagif Abilov says:

    Brad, you didn’t mention anything about namespace naming convention. Namespaces usually follow assembly names, but should be there any exceptions? Can assembly contain more than one namespace? Or one namespace be spread across multiple assemblies?

  51. Kevin Westhead says:

    John,

    I took Larry’s comment as being in favour of spaces, since this is the only way to preserve the original formatting.

    e.g. someone might prefer to format a pinvoke signature as follows:

    [DllImport("foo.dll"]

    static extern bool Bar( string myString,

    bool myBool,

    ref bool myBoolRef );

    If the indents on the last two lines are made up of tabs, then your tab size has a big impact on the resulting format. While many people might not like the style of formatting above, with spaces instead of tabs you’ll at least get the chance to view the code instead of it possibly being tabbed off-screen to the right.

  52. Kevin Westhead says:

    Damn, the formatting’s been lost. The parameter definitions were supposed to be aligned, i.e. "bool" directly under "string" and "ref" directly under "bool".

  53. Moily says:

    As a "Born Again TABber", TABs are the only way to go. I find 2-spaces-per-TAB the ideal indentation, but one colleague always used to indent with 4 space character TABs and another with 8 (!!).

    However, thanks to the editor settings I can view their code at my preferred setting of 2-spaces-per-TAB while they see their code in their preferred format. Everyone’s happy!

    Anyway, on another point: how about adding a section on outlawing the evil ‘break’ and ‘goto’ statements, and only having one ‘return’ statement as the last line of the method? Having multiple exit points from a code block is a nightmare to debug and is soooo wrong.

    I propose a ‘goto/break’ amnesty for all code written before today, but anyone caught using them from now on should be made to pay a forfeit!

  54. Stan says:

    I think tabs should be used. Maybe I don’t personally like someone else’s 2 space indenting. If it is done using a 2-space tab, I can read the code with my 4-space tab when I bring it into my editor. I you want to read it with a 6-space tab, it works. Even though I personally do agree on a 4-space indention, you may not want to be subject to it. Tabs allow it to be seen your way.

  55. Stan says:

    I think tabs should be used. Maybe I don’t personally like someone else’s 2 space indenting. If it is done using a 2-space tab, I can read the code with my 4-space tab when I bring it into my editor. I you want to read it with a 6-space tab, it works. Even though I personally do agree on a 4-space indention, you may not want to be subject to it. Tabs allow it to be seen your way.

  56. John Wood says:

    Kevin,

    My recommendation is not to layout your parameters in that way – keep them all on the same line, or put ALL parameters on separate lines. Otherwise you’re just asking for layout issues…

  57. JD says:

    The issue is with tabs and spaces *mixed*.

    If the file is consistent either way it won’t matter, really.

    Spaces have the advantage:

    1. Will always display the same (as the author intended)

    2. Not all editors support your favorite tabstop settings [Notepad uses 8-space tabs, I use 4-space tabs. Spaced files look fine.]

    3. It’s easy to replace tabs with spaces via a tool. [you can’t do this in reverse as easily]

    4. With ‘visible tabs’ turned on in an editor, it’s easy to keep the file clean. [conversely, you can’t ban spaces]

    Tabs have the advantage:

    1. Can display differently according to the user’s editor. This should closer match their interest.

    2. Simple editors use tabs (with the TAB key). Only programmer editors subtitute spaces for tabs automatically. [So editing a ‘tabbed’ document in Notepad is easier. With a ‘spaced’ document you will likely introduce new tabs without realising it]

    3. Tabs tend to be the default in most editors. So if you reinstall the editor on a new machine, you’re likely ending up with tabs.

    Conclusion: Tabs allow for better editing with simple tools, and allow for more flexible display in advanced tools.

    Spaces, on the other hand, are easier to enforce with tools and display more consistently across various outputs.

    For me, spaces win due to being easier to enforce. I can run a tool over the source files and eliminate tabs, and have a consistent codebase. I cannot as easily go from a mixed codebase and eliminate spaces.

  58. Stan says:

    What about controls? txtName, lblName, etc?

  59. Peter Gfader says:

    I agree with the brace rule above!

    Always braces and always tabs, for the reasons you all have written.

    ——-

    One of our naming rules, that doesn’t correspond with the MS rules:

    Variables that contain GUI elements should be prefixed.

    <Not Microsoft like!>

    Microsoft recommends suffixing Fields and variable names, but it’s easier to handle prefixed variables in Visual Studio (Renaming in Form Designer, searching with Code completion).

    // Avoid

    System.Windows.Forms.Button cancelButton;

    System.Windows.Forms.TextBox nameTextBox;

    // Correct

    System.Windows.Forms.Button buttonCancel;

    System.Windows.Forms.TextBox textBoxName;

    What do you think about?

  60. Anonymous says:

    Erick Sasse &raquo; C# Coding Guidelines

  61. Всё очень просто с ними, но некоторые вещи мне кажутся неудобными

  62. Tom Degen says:

    I noticed a lot of people complaining (?)… lamenting about the use of 4 spaces instead of a tab.

    Did you know that Visual Studio (and other IDEs) allow you to set your tab key to include spaces instead of the tab character?

    This way everyone gets what they want… an easy to use tab key AND spaces so that every editor looks the same.

  63. Babu Aboobacker says:

    Thanks Tom.It is so easy and useful.

  64. Paul Cotter says:

    Provided …

    1) the editor stores data in a single format regardless of whether it is displayed as tabs or spaces

    2) You preserve the ‘look’ of the source file, and the ‘feel’ of the code

    … it matters little (I’m a little tabby cat personally)

    In terms of removing goto, it should be gone, except it still has one use for me. I find it useful if the code is going to be generated by another program rather than manually. A decision-table matrix lends itself to this use.

    After all – the compiler does it…

  65. Jiho Han says:

    What is the reason for nesting Using statements inside namespace block?

  66. leppie says:

    "All interop classes must be private, and all methods must be internal."

    Classes cant be private at assembly level, marking methods on those classes (whether internal or nested private) ‘internal’ has NO effect on access.

  67. A little inconsistancy? says:

    <Wine mode>

    At the end of paragraph 2.2 it says "Braces should never be considered optional."

    However it ends paragraph 2.3 with "It is suggested that all control structures (if, while, for, etc.) use braces, but it is not required."

    </Wine mode>

    Thanks for the document, I’ll use this to slap the devs on my team. 😉

  68. <p>I found a post on one of the MSDN blogs the other day about Hungarian Notation being adopted by some of the Microsoft Development teams, and how they should go about using it.</p><p>Where I work, we don’t use Hungarian Notation, and so far we have managed to cope without it. Having said that, the language that we use (Progress 4GL) is meant for database access, and therefore relatively few types actually exist, and more complex types are created by creating database tables. The most that we really stretch to is "vVarName" for a variable, "ipParamName"/"opParamName"/"iopParamName" for input/output/input-output parameters (respectively). Some people do go further and may use "c" for a string, but that is about it. We also call procedures or functions defined in include-files "i_ProcName" to make it easier to identify their location, and sometimes people may name variables inside of procedures located in include files so that they do not run into "Multiple Variable Declaration" problems.. So far, in the extensive project that I work on, it’s not been a problem.</p><p>The also to a page which describes an internal Microsoft layout format for programs/source code. Again, we don’t have a strict set of rules for this. We have rough guide lines (like "Line up all the equal signs") but quite often these are broken in order to actually improve readability.</p><p>What this actually means though, is that (by knowing each person’s individual style), it can be quite easy to pin-point who did a piece of work where it is not already obvious who had done the work.</p><p>I doubt that my Project Managers will ever feel the need to develop a more rigorous standard, or enforce rules about layout and style, and for the most part I don’t think that we will need to either.</p><p>We’ll just have to see what happens with time…..</p>

  69. Coding guidelines that serve to extend and enhance the Microsoft .NET Framework Design Guidelines for the Visual Basic .NET developer.

  70. Coding guidelines that serve to extend and enhance the Microsoft .NET Framework Design Guidelines for the Visual Basic .NET developer.

  71. Want to know how microsoft developer write their codes? well Brian Abrams has posted thier coding guidlines…

  72. If you’ve ever tried to discuss coding standards, you’ve realized that we

    have a long way to go before…

  73. A collection of Coding Guidelines and Standards in C# and VB.NET

  74. A collection of Coding Guidelines and Standards in C# and VB.NET

  75. Keith Rull says:

    Here are some useful links that tackle programming guidelines on C# and VB.NET.

    VB.NET Coding Guidelines…

  76. Keith Rull says:

    Here are some useful links that tackle programming guidelines on C# and VB.NET.

    VB.NET Coding Guidelines…

  77. Good programming involves more than just coding. The links available in the side bars are already enough…

  78. Scott Munro says:

    I asked for some comments regarding my post on the practice of camel casing private members in my DotNetJunkies…

  79. The following links to .NET resources have been collated over time with the assistance of colleagues.&amp;nbsp;…

  80. jokiz's blog says:

    I started programming with C and used Hungarian notation since then. It was very helpful back then to

  81. Finally my blogs up!! Thanks David!Looking to blog from the yesterday, finally here I &quot;start&quot;. Welcome…

  82. Scott Davis says:

    Today we embarked on the process of creating company coding standards.&amp;nbsp; This is alwyas fun as developers…

  83. .NET Custom Forms Designer: Name Creation Service

  84. Buspar. says:

    Does buspar work. Buspar and hostility. Buspar experience. Buspar anxiety. Buspar. Buspar alcohol.