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 { … }

}

}

Published 26 January 05 10:13 by BradA

Comments

# Adarsh Bhat said on January 27, 2005 12:37 AM:
This is really useful. Thanks.
# Matt Hall's Blog said on January 27, 2005 3:51 AM:
# Matt Hall's Blog said on January 27, 2005 3:56 AM:
# Di .NET e di altre amenita' said on January 27, 2005 3:57 AM:
# Sam said on January 27, 2005 1:21 AM:
>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
# Samuel Jack said on January 27, 2005 1:51 AM:
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."

# mihailik said on January 27, 2005 4:07 AM:
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.
# mihailik said on January 27, 2005 4:11 AM:
You didn't state that. Do you really use camelCase for private constants?
# Kevin Westhead said on January 27, 2005 4:37 AM:
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 \sscli\clr\src\bcl\system\appdomain.cs but the last ones are defined in \sscli\clr\src\bcl\system\unhandledexceptioneventargs.cs and \sscli\clr\src\bcl\system\unhandledexceptioneventhandler.cs.

Ultimately though, the important thing (as far as naming is concerned) is that each type conforms to the naming guidelines for events.
# Sam said on January 27, 2005 4:51 AM:
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)?
# Stuart said on January 27, 2005 4:54 AM:
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;

# G. Man said on January 27, 2005 6:35 AM:
>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.

# andyBlog said on January 27, 2005 9:44 AM:
MS coding style
# Kevin Westhead said on January 27, 2005 7:02 AM:
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
# Blog de Jose Luis Manners said on January 27, 2005 10:07 AM:
# Jose Luis Manners' Blog said on January 27, 2005 10:45 AM:
# Jose Luis Manners' Blog said on January 27, 2005 11:23 AM:
# Hello??? .... is this thing on?? said on January 27, 2005 11:46 AM:
# Grim said on January 27, 2005 9:05 AM:
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>
# Larry Osterman's WebLog said on January 27, 2005 1:00 PM:
# Keith Patrick said on January 27, 2005 10:42 AM:
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)
# bramster said on January 27, 2005 11:10 AM:
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.
# C#deSamurai said on January 27, 2005 2:24 PM:
# Marcos said on January 27, 2005 11:25 AM:
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.
# Brian said on January 27, 2005 11:58 AM:
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.
# TheChaseMan's Frenetic SoapBox said on January 27, 2005 3:10 PM:
# Aviator said on January 27, 2005 12:14 PM:
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".
# .Net Adventures said on January 27, 2005 3:24 PM:
# Drew Marsh said on January 27, 2005 12:31 PM:
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?
# Robert Jeppesen said on January 27, 2005 2:45 PM:
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.
# Kevin Westhead said on January 27, 2005 2:58 PM:
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
# Anatoly Lubarsky: T-SQL Weblog said on January 27, 2005 6:34 PM:
# Eric Gunnerson's C# Compendium said on January 27, 2005 11:57 PM:
# Uwe Keim said on January 27, 2005 9:06 PM:
Is there a FxCop rule for your coding styles?
# Dale Thomas said on January 27, 2005 9:18 PM:
This is great stuff.
# Nader Soliman said on January 27, 2005 9:25 PM:
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? ;)
# Cyrus Najmabadi said on January 27, 2005 10:29 PM:
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?
# Ahmed Salijee said on January 28, 2005 2:37 AM:
# Cleve Littlefield said on January 27, 2005 11:53 PM:
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...
# Cook Computing said on January 28, 2005 3:07 AM:
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...
# Jørn said on January 28, 2005 12:08 AM:
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+"\">");
# www.vittrup-graversen.dk said on January 28, 2005 4:22 AM:
# Mihir Solanki said on January 28, 2005 1:25 AM:
Well, I dont think its good idea to use 4 spaces instead of tab.It unnecessarily increase editing complexity.
# www.vittrup-graversen.dk said on January 28, 2005 4:26 AM:
# David's blog said on January 28, 2005 5:23 AM:
# David's blog said on January 28, 2005 5:24 AM:
# Dave said on January 28, 2005 2:29 AM:
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!
# AM said on January 28, 2005 2:30 AM:
"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.
# Jack said on January 28, 2005 2:44 AM:
camelCasingMakesCode less_readable_than_underscores
# Alex said on January 28, 2005 2:54 AM:
>>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);
# John Brennan's Blog said on January 28, 2005 7:27 AM:
# Sam said on January 28, 2005 5:46 AM:
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.
# TrackBack said on January 28, 2005 9:02 AM:
An excellent post by Brad Abrams deta...
# AndrewSeven said on January 28, 2005 6:25 AM:
"Tab characters (\0x09) 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.


# mihailik said on January 28, 2005 7:06 AM:
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.
# Dela's Ramblings said on January 28, 2005 10:31 AM:
# Dela's Ramblings said on January 28, 2005 10:32 AM:
# Jeffrey Palermo said on January 28, 2005 11:34 AM:
Coding standards from Microsoft - level 100
# Craig said on January 28, 2005 9:37 AM:
"Tab characters (\0x09) 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.
# Javier G. Lozano said on January 28, 2005 1:54 PM:
# Qju's Blog said on January 28, 2005 2:27 PM:
# J. Daniel Smith said on January 28, 2005 12:59 PM:
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.
# michael stromberg said on January 28, 2005 4:26 PM:
A bit of reflection of my own coding style in comparison to other established coding styles at Sun, SGI, and Microsoft.
# michael stromberg said on January 28, 2005 4:27 PM:
A bit of reflection of my own coding style in comparison to other established coding styles at Sun, SGI, and Microsoft.
# enders said on January 28, 2005 3:02 PM:
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
# David Hayden - Sarasota Web Design Development - F said on January 28, 2005 7:58 PM:
# David Hayden - Sarasota Web Design Development - F said on January 28, 2005 7:58 PM:
# .NET Addicted said on January 29, 2005 7:36 AM:
# .NET Addicted said on January 29, 2005 7:37 AM:
# John Wood's Blog said on January 29, 2005 8:45 PM:
Thoughts on Naming Convention
# John Wood's Blog said on January 29, 2005 11:25 PM:
Tabs for Indenting Code
# Steve said on January 29, 2005 9:15 PM:
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.
# 米田 Blog ( SQL Server MEMO ) said on January 30, 2005 9:19 AM:
Internal Coding Guidelines (C# マイクロソフト)
# Vince Pacella said on January 30, 2005 8:10 AM:
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.

# Joe said on January 30, 2005 11:42 AM:
> 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.
# Larry Osterman said on January 30, 2005 4:43 PM:
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.
# John Wood said on January 30, 2005 5:30 PM:
Larry,
Absolutely right. I really don't get where Brad is coming from here. I hope he speaks up on it at some point.
# Vagif Abilov said on January 31, 2005 12:10 AM:
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?
# Kevin Westhead said on January 31, 2005 7:40 AM:
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.
# Kevin Westhead said on January 31, 2005 7:43 AM:
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".
# Moily said on January 31, 2005 8:22 AM:
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!



# Stan said on January 31, 2005 8:52 AM:
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.
# Stan said on January 31, 2005 8:54 AM:
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.
# John Wood said on January 31, 2005 9:28 AM:
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...
# JD said on January 31, 2005 11:23 AM:

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.

# Stan said on January 31, 2005 1:49 PM:
What about controls? txtName, lblName, etc?
# Agus Kurniawan said on February 1, 2005 2:09 AM:
# Peter Gfader said on January 31, 2005 11:48 PM:
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?
# TrackBack said on February 1, 2005 6:51 AM:
Erick Sasse &raquo; C# Coding Guidelines
# Denis's Blog [notes about toolkit creation] said on February 2, 2005 4:28 AM:
Всё очень просто с ними, но некоторые вещи мне кажутся неудобными
# Woong said on February 2, 2005 7:59 PM:
Thanx
# Tom Degen said on February 3, 2005 4:05 PM:
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.
# Babu Aboobacker said on February 3, 2005 11:41 PM:
Thanks Tom.It is so easy and useful.
# blog.dreampro said on February 5, 2005 11:48 PM:
# Paul Cotter said on February 8, 2005 2:39 PM:
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...
# Cadred.NET said on February 14, 2005 5:29 PM:
# Jiho Han said on February 15, 2005 8:44 AM:
What is the reason for nesting Using statements inside namespace block?
# #region Coad's Code said on February 19, 2005 11:23 PM:
# leppie said on February 21, 2005 10:42 PM:
"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.
# A little inconsistancy? said on February 22, 2005 8:46 AM:
<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. ;)
# Cyrus' Blather said on March 8, 2005 5:35 AM:
# Eric Gunnerson's C# Compendium said on March 9, 2005 12:00 PM:
# Armswiper's Blog said on March 9, 2005 3:48 PM:
<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>
# .Net Security Blog said on March 16, 2005 6:37 PM:
# AddressOf.com said on March 16, 2005 11:02 PM:
Coding guidelines that serve to extend and enhance the Microsoft .NET Framework Design Guidelines for the Visual Basic .NET developer.
# AddressOf.com said on March 16, 2005 11:35 PM:
Coding guidelines that serve to extend and enhance the Microsoft .NET Framework Design Guidelines for the Visual Basic .NET developer.
# AddressOf.com said on March 17, 2005 12:49 AM:
# Brad McCabe's WebLog said on March 18, 2005 3:55 PM:
# Brad McCabe's WebLog said on March 18, 2005 3:56 PM:
# AddressOf.com said on March 18, 2005 6:02 PM:
# Gianluca's Blog said on March 26, 2005 4:28 PM:
# Rob Windsor's Weblog said on March 26, 2005 11:52 PM:
# Rob Windsor's Weblog said on March 27, 2005 1:00 AM:
# Scott Bellware's Webflog said on March 28, 2005 1:38 PM:
# Gump's blog said on April 6, 2005 5:02 AM:
# Gump's blog said on April 6, 2005 4:56 AM:
# Daily Flash Indonesia said on April 7, 2005 1:20 AM:
Want to know how microsoft developer write their codes? well Brian Abrams has posted thier coding guidlines...
# Ian Blackburn's Weblog said on April 13, 2005 4:35 AM:
# Ian Blackburn's Weblog said on April 13, 2005 6:41 AM:
# Little Tidbits of Random Knowledge said on April 22, 2005 4:11 PM:
# The Right Tempo said on April 28, 2005 11:51 AM:
# Jeffrey Palermo said on June 29, 2005 12:08 PM:
If you've ever tried to discuss coding standards, you've realized that we
have a long way to go before...
# .NET Hobbyist Programmer said on June 30, 2005 10:35 PM:
# keithrull.com: a technology hub for geeks said on August 19, 2005 1:05 AM:
A collection of Coding Guidelines and Standards in C# and VB.NET
# keithrull.com: a technology hub for geeks said on August 19, 2005 1:07 AM:
A collection of Coding Guidelines and Standards in C# and VB.NET
# Keith Rull said on August 19, 2005 1:09 AM:
Here are some useful links that tackle programming guidelines on C# and VB.NET.
VB.NET Coding Guidelines...
# Keith Rull said on August 19, 2005 1:09 AM:
Here are some useful links that tackle programming guidelines on C# and VB.NET.
VB.NET Coding Guidelines...
# Keith Rull said on August 19, 2005 1:16 AM:
# Sheva said on January 30, 2006 10:09 AM:
TrackBack From:http://sheva.cnblogs.com/archive/0001/01/01/324297.html
# Prabhuram Venkatesan said on February 11, 2006 6:03 PM:
Good programming involves more than just coding. The links available in the side bars are already enough...
# mBLOG » Coding Guidelines C# said on February 22, 2006 8:37 AM:
PingBack from http://www.mbartels.com/index.php/2006/02/22/coding-guidelines-c/
# Scott Munro said on March 11, 2006 2:27 PM:
I asked for some comments regarding my post on the practice of camel casing private members in my DotNetJunkies...
# Walkdan said on March 31, 2006 4:16 AM:
TrackBack From:http://walkdan.cnblogs.com/archive/2006/03/31/363768.html
# Walkdan said on March 31, 2006 4:26 AM:
TrackBack From:http://walkdan.cnblogs.com/archive/0001/01/01/363768.html
# mattonsoftware.com said on May 6, 2006 4:29 AM:
The following links to .NET resources have been collated over time with the assistance of colleagues.&amp;nbsp;...
# Black-Log said on May 22, 2006 6:05 PM:
# briandela said on June 1, 2006 9:53 AM:
# jokiz's blog said on August 11, 2006 7:21 AM:
I started programming with C and used Hungarian notation since then. It was very helpful back then to
# Welcome to VJ's World said on August 31, 2006 2:41 AM:
Finally my blogs up!! Thanks David!Looking to blog from the yesterday, finally here I &quot;start&quot;. Welcome...
# Scott Davis said on September 22, 2006 8:53 AM:
Today we embarked on the process of creating company coding standards.&amp;nbsp; This is alwyas fun as developers...
# .NET Hobbyist Programmer said on October 18, 2007 6:12 PM:

.NET Custom Forms Designer: Name Creation Service

New Comments to this post are disabled

Search

Go

This Blog

Syndication

Page view tracker