C#.NET Coding Standards and Guidelines

This is the current set of coding standards and guidelines I use when I’m coding in the C#.NET language.
I thought it would be good to share so others could get use out of them also, and maybe start a discussion as to amendments / changes they see that could be useful?

Naming Conventions

  • Do not use Hungarian notation, I.E. a boolian variable may have the name MyBool, but shouldn’t be called bMyBool.
  • Do prefix member variables with the underscore ‘_’. Do not prefix member variables with “this”. also use camelCasing for member variables. The underscore is easy to see, is one key stroke.
  • Do prefix interfaces names with “I”
  • Do not prefix enums, classes, or delegates with any letter.

Key:

c” = camelCase
P” = PascalCase
“_” = Prefix with _Underscore
“x” = Not Applicable.

Identifier Public Protected Internal Private Notes
Project File P x x x Match Assembly and Root Namespace
Project Folder P x x x Match Project File
Source File P x x x Match contained class
Test Source File P x x x Append the word Test if it contains tests
Image File c x x x
Other Files P x x x Apply where possible
Namespace P  x x x Partial Project/Assembly match.(Also see the namespace section)
Solution File P x x x CompanyNameSolutionDescription
Solution Folder P x x x CompanyNameSolutionDescription (if multiple solutions in repository). Source (if single solution)
SpecFlow Feature File P x x x USn_BriefUserStoryName where n is the user story number
oject Folder P  x x x Same as Project file
Class or Struct P P P P Add suffix of subclass.
Interface P P P P Prefix with a capital I.
Generic Class P P P P Use T (type) or K (key) as Type identifier.
Method P P P P Use a Verb or Verb-Object pair.
Test Method P x x x MemberUnderTest_StateUnderTest_ExpectedBehavior . StateUnderBehavior can be leftout if not applicable.
Property P P P P Do not prefix with Get or Set.
Field P P P _c Only use Private fields.
Constant P P P _c
Static Field P P P _c Only use Private fields.
Enum P P P P Options are also PascalCase.
Delegate P P P P See under Events, Delegates for naming Dot NET
Event P P P P See under Events, Delegates for naming Dot NET
Inline Variable x x x c Avoid single-character and enumerated names.
Parameter x x x c

Coding Style

Commenting

Comment Style

Block comments should usually be avoided

/* Line 1
* Line 2
* Line 3
*/
/* … */

Begin comment text with an upper case character. End comment text with a period.

If you have to comment your code, consider refactoring, so that it is easier to read.
Prefer not to use inline-comments to explain obvious code. Well written code is self-documenting.
Rather fix or clean up code now, than put a // Todo in.

You can access // Todo‘s in Visual Studio via

View menu -> Task List
The Tokens can be setup in Tools -> Options… -> Environment->Task List

or for ReSharper

ReSharper menu -> Tools -> To-do Items (or use the key shortcuts)

Use the following tokens:

  • Todo
  • Note
  • Bug
  • Not Implemented

XML Documentation

  • Always apply C# comment-blocks (///) to public, protected, and internal declarations.
  • Only use C# comment-blocks for documenting the API I.E the interface.
  • include <summary> comments. Include <param>, <return>, and <exception> comment
    sections where applicable.
  • Include <see cref=””/> and <seeAlso cref=””/> where possible.
  • Always add CDATA tags to comments containing code and other embedded markup in order to avoid
    encoding issues.
    Example:

    ///
    /// Add the following key to the appSettings” section of your config:
    /// <code><![CDATA[
    ///   <configuration>
    ///     <appSettings>
    ///       <add key=”mySetting” value=”myValue”/>
    ///     </appSettings>
    ///   </configuration>
    /// ]]></code>
    ///
    

File Organisation

Group internal class implementation by type in the following order:

  1. Member variables.
  2. Constructors & Finalizers.
  3. Nested Enums, Structs, and Classes.
  4. Properties
  5. Methods

Sequence declarations within type groups based upon access modifier and visibility:

  1. Public
  2. Protected
  3. Internal
  4. Private
  • Do not use #region statements
  • Always match class name and file name where ever possible. Avoid including more than one class per file.

Formatting

Bracing

  • Place first brace of the block at the end of the line preceded with a space.
    In languages like C, C++, C#, Java, it doesn’t matter where you put the first curly brace, it’s just personal preference or based on vote.
    In languages like JavaScript, it does matter. I use quite a bit of JavaScript, so just find it easier to use the same convention. Although at work, we use the “opening brace on a new line convention, simply because it won the vote”.
  • Always use curly braces ({ and }) in conditional statements. Unless there is a very simple statement, like return bla.
  • Recursively indent all code blocks contained within braces.

Spacing

Use white space (CR/LF, Tabs, etc) liberally to separate and organize code.

Only declare related attribute declarations on a single line, otherwise stack each attribute as a separate declaration.

Example:

// Bad!
[Attrbute1, Attrbute2, Attrbute3]
public class MyClass {
   …
}

// Good!
[Attrbute1, RelatedAttribute2]
[Attrbute3]
[Attrbute4]
public class MyClass {
   …
}

Tabs and Indenting

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

Language Usage

Access Modifiers

Do not omit access modifiers.
Explicitly declare all identifiers with the appropriate access modifier instead of allowing the default.
Example:

// Bad!
Void WriteEvent(string message) {
   …
}

// Good!
private Void WriteEvent(string message) {
   …
}
Prefer explicit to implicit Both the above definitions are private.
Prefer explicit to implicit.

Calling Routines

When calling a routine that takes a bool or a number.
Don’t pass litterals, as it’s unclair what they represent.
Instead create a variable with a meaningful name.

// calling MethodTakingExampleArgs
MethodTakingExampleArgs(true, 12);

// instead do the following

bool temperatureHasChanged = true;
int temperatureInCelcius = 12;

// calling MethodTakingExampleArgs
MethodTakingExampleArgs(temperatureHasChanged, temperatureInCelcius);

The intent becomes clearer, thus making for code that’s easier to read, thus we work faster.

If a routine call has its parameters spread over more than a single line due to being to long, place each parameter on its own line.
Also consider how many arguments are being passed, if it’s over 5, consider other ways to pass the information needed.

Class

Avoid putting multiple classes in a single file.

Events, Delegates

The delegate type should be prefixed with “Handler”.
The name of the procedure that does the work should be a verb.

public class MyDelegateExample {
   delegate void ChangeHandler();
   event ChangeHandler _change;

   private void OnChange() {
      if (_change != null)
         _change();
   }
}
Prefer explicit to implicit Rather than checking for null, you can add an empty delegate to your _change event
so that you don’t have to check the event for null before you raise it.

The traditional null check followed by the next action is not atomic, so not thread safe. Discussed in more depth here.

public class MyDelegateExample {

   delegate void ChangeHandler();
   event ChangeHandler _change = delegate{};

   public void Attach(ChangeHandler update) {
      Change += update;
   }

   public void Detach(ChangeHandler update) {
      Change -= update;
   }

   private void OnChange() {
      _change();
   }
}

Exceptions

  • Do not use try/catch blocks for flow-control. Only use for exceptional cases.
  • Only catch exceptions that you can handle.
  • Never declare an empty catch block.
  • Avoid nesting a try/catch within a catch block.
  • Always catch the most derived exception via exception filters.
  • Order exception filters from most to least derived exception type.
  • Avoid re-throwing an exception. Allow it to bubble-up instead.
  • If re-throwing an exception, preserve the original call stack by omitting the exception argument from the throw statement.Example:
    // Bad!
    catch(Exception e) {
       Log(e);
       throw e;
    }
    
    // Good!
    catch(Exception e) {
       Log(e);
       throw;
    }
    
  • Only use the finally block to release resources from a try statement.
  • Always use validation to avoid exceptions.
    Example:

    // Bad!
    try {
       conn.Close();
    }
    Catch(Exception ex) {
       // handle exception if already closed!
    }
    
    // Good!
    if(conn.State != ConnectionState.Closed) {
       conn.Close();
    }
    
  • Always set the innerException property on thrown exceptions so the exception chain & call stack are maintained.
  • Avoid defining custom exception classes if there is an existing Exception derived class available in the .NET library.
  • Always suffix exception class names with the word “Exception”.
  • Always add the SerializableAttribute to exception classes.
  • Always implement the standard “Exception Constructor Pattern”:
    public MyCustomException ();
    public MyCustomException (string message);
    public MyCustomException (string message, Exception innerException);
    
    Prefer explicit to implicit Or better… if using .NET 4.0 or greater, use optional parameters.
  • Always implement the deserialization constructor:
    protected MyCustomException(SerializationInfo info, treamingContext contxt);
    

Flow Control

Case Statements

  • Only use switch/case statements for simple operations with parallel conditional logic.
  • Prefer nested if/else over switch/case for short conditional sequences and complex conditions.
  • Prefer polymorphism over switch/case to encapsulate and delegate complex operations.
    Don’t fall into the trap of writing procedural code in an OO language.

Conditions

Avoid evaluating Boolean conditions against true or false.
Example:

// Bad!
if(isValid == true) {
   …
}

// Good!
if(isValid) {
   …
}

Use braces {} as shown above in all situations but for the most simple.
If you have more than a single line statement in a conditional, surround it with braces.

Implicit typing using the var keyword

Some background on var:

The compiler simply takes the compile time
type of the initialization expression and makes the variable have that type too.
An example:

var stringVariable = "Hello, world."
stringVariable = 0;
The above code is invalid.

The var keyword should only be used with LINQ and Anonymous types.
Unless there’s a significant gain in code simplicity, use explicit typing.

It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types.
See Microsofts reference on var.

Sometimes you actually want the code to break when a type is changed.

Consider a control system. Many elements have On() and Off() methods. there are many cases where there is no relationship between the types (i.e. no common base classes or interfaces), there is only the similarity that both have methods with those signatures.

Writting code:

var thing = SomeFactory.GetThing();  // Returns something that is safe to turn off...
thing.Off();

Then later a change is made to the Factory and that method now returns something completely different, which happens to have severe consequences if it is arbitrarily turned off having such a design is debatable for many reasons.

By using var, the previous code will compile without complaint. Even though the return type may have changed from ReadingLamp to LifeSupportSystem.

I believe that there are more times when there is the possibility of an “unintended side-effect” caused by a change in the type than there are times where the change in type has no bearing on the code that consumes it. As a result, I very rarely use var. Even when the return type is obvious (such as the LHS of a new), I find it easier to be consistent.

Namespace

  • CompanyName.SolutionDescription.AssemblyDescription
  • Never declare more than 1 namespace per file.
  • Append folder-name to namespace for source files within sub-folders.
  • Also see the Naming conventions table.
  • Place namespace “using” statements together at the top of file. Group .NET namespaces above custom namespaces.
  • Followed by grouping of external namespaces.
  • Followed by grouping of organisation namespaces.
  • Order namespace “using” statements alphabetically.

Variables and Types

  • Declare and preferably initialize local variables at the same point and as close to where you first use them.
  • Always choose the simplest data type, list, or object required.
  • Always use the built-in C# data type aliases, not the .NET common type system (CTS).
    Example:
short NOT System.Int16
int NOT System.Int32
long NOT System.Int64
string NOT System.String
  • Declare one variable per line.
  • Only declare member variables as private. Use properties to provide access to them with public, protected, or internal access modifiers.
  • Prefer to use the as operator and check for null, rather than directly casting, and having to handle potential InvalidCastException.
    object dataObject = LoadData();
    DataSet ds = dataObject as DataSet;
    if(ds != null) {
       …
    }
    
  • Avoid boxing and unboxing value types.
    Especially in loops, or where performance matters.Example:

    int count = 1;
    object refCount = count; // Implicitly boxed.
    int newCount = (int)refCount; // Explicitly unboxed.
    

Strings

  • Use the “@” prefix for string literals instead of escaped strings.
  • Prefer String.Format() or StringBuilder over string concatenation.
    StringBuilder performs many times faster (thousands in fact)
  • Never concatenate strings inside a loop. Remember, string’s are immutable. Each time you concatenate, a new instance of string is created.
  • Checking whether a string is empty?
    String.Length == 0 or “” is faster than String.Empty, but… beware of null strings, if null when you perform a String.Length, you’ll get a NullReferenceException.
    The safest technique is to use the static IsNullOrEmpty function on string.
    Using “” does not create a new object. Due to string interning, it will be created either once per assembly or once per AppDomain.
Advertisements

Tags:

24 Responses to “C#.NET Coding Standards and Guidelines”

  1. Dave Says:

    The title of the link to Microsoft’s page on implicit typing using the var keyword is inaccurate. The linked page is just a reference and not a recommendation. Personally I use var whenever possible/appropriate and there doesn’t appear to be any reason provided for your own recommendation to “use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types.” To me, var is a great way to have static typing without having to repeat the type in both the declaration and object creation, which can quickly become annoying, especially when instantiating generics.

  2. binarymist Says:

    Updated title. Thanks Dave.
    There are many arguments for and against the use of var.
    The debates will continue for as long as the language is used.
    var when used outside of its intended purpose, should follow the principle of least astonishment (POLA).
    The intended purpose is stated here http://msdn.microsoft.com/en-us/library/bb384061%28VS.90%29.aspx as I’ve stated above.
    As stated in the Remarks section “However, the use of var does have at least the potential to make your code more difficult to understand for other developers.”
    Code is read 10 times more than it is written.
    So the number one rule is: Keep it easily readable.

  3. davidvclarke Says:

    I tend to concur with Resharper which always suggests replacing the explicit declaration with an implicit var declaration. Personally I find it far easier to read var declarations because they are briefer so it’s not just about reducing the amount of typing but displaying the declaration in a form that’s easy to digest. YMMV.

  4. freeranger Says:

    Agreed with Dave, and indeed the Microsoft “intended usage” suggests it “can also be useful when the specific type of the variable is tedious to type on the keyboard, or is obvious, or does not add to the readability of the code.”
    Which very often is the case – I don’t really care if this is an int or a long, just that it is a variable used in a loop, and I don’t want to be bogged down e.g. reading a declaration like this:

    Dictionary<string, List> dict = new Dictionary<string, List>();

    var dict = new Dictionary<string, List>();

    Does just fine thanks. Sure, sometimes it is more helpful to see the type declared explicitly, but very often it is just noise…

    On another point in your coding standards, you seem a little inconsistent in that you say comments should be avoided, if you need to comment your code, consider refactoring to make it more readable, but later you say that public, protected, and internal declarations should always have /// comment blocks.
    I agree with the former, which should negate the need for the latter.
    If I have a method:

    public void IncreaseTemperatureBy(int increaseInTemperature)

    Then /// commenting the method name and params adds no value whatsoever. For some methods, sure, you may want to provide a code sample of usage, or some description of it if it is particulately complex etc, but generally, commenting method names and params adds noise and is just more stuff to refactor if you go changing method or param names at some point

    • binarymist Says:

      freeranger:

      Code comments vs API (Xml) comments have two completely different purposes.

      The former is for explaining what, how, why the developer coded something a certain way.
      These are to be read inline with the code, but I’d prefer if you could just refactor your code to be more self explanatory.

      API (Xml) comments are used by tools such as Sandcastle and NDoc to generate API documentation, and also the Intellisense you rely on so heavily when using the likes of the var keyword to tell you what the types are.

      So it’s not an inconsistency your seeing, but rather consistent advice on how, when, and where to use two different types of comments for two quite different purposes.

      When your thrown into an existing project that has a complex domain that you don’t fully understand.
      You will be very thankful for any documentation you can get your hands on.
      API (Xml) documentation that has been conscientiously written may form a key part of the generated document.

      When you use someone else’s library API, same thing applies.
      Often it’s generated documentation you’ll be reading.
      MSDN is a prime example.

      Does that makes sense?

      • freeranger Says:

        Well named methods and parameters (increaseInTemperature rather than “i” for example should be sufficient – there is no need for:
        /// Represents the increase in temperature

        Yes, sometimes methods and parameters warrant further explanation, possibly with code samples, but very often they are redundant, so don’t be proscriptive about this.
        Also, documentation is only up to date at the point you write it – all too often it becomes redundant as the developer fails to keep it up to date with his refactoring. I don’t know any developer who would take this sort of XML documentation as gospel and all too often I see comments for parameters or methods which have been renamed or removed, but the comment is left behind (resharper will point these out) as just so much dead wood.
        Of course this sort of thing shouldn’t happen, everyone should ensure their comments and code match, but in the real world, in my experience, that rarely happens.

        I’d much rather see a comprenensive suite of unit tests as “living documentation” for the api, which is guaranteed to be up to date (if the tests are all green of course) and provides a useful example of usage.

        All too often I see, (and 3rd party component vendors are often as guilty of this as in house developers), a set of documentation which is little more than ghost-scripted XML doc comments listing methods and params and “cleverly” separating your pascal or camel cased names into separate words. This looks like you have produced somehing worthwhile because you have “documentation” but actually it tells you nothing more than you would get from looking at the method signatures directly.

        I would rather someone spent the time writing useful documentation (if the test suite is not sufficient) than just robotically documenting every public method they create.

        Actually that reminds me, you say that internals should be documented too. If they are for internal use only and not part of your public api then they won’t (or shouldn’t) appear in any APi documentation anyway, so would seem doubly-redundant in this case.

  5. janvanderhaegen Says:

    Nice one, thanks!

    PS: “If you have more than a single line statement in a conditional, surround it with braces.” -> if you have more than a single line statement, you HAVE to surround it with braces or it won’t compile (at best) or compile to unexpected behaviour (at worst)

  6. binarymist Says:

    freeranger:

    Thanks for the comments.

    I’m All for naming API members or all members descriptively for that matter.
    Sometimes the name doesn’t give enough information about what’s actually going on inside the routine to be able to use it… without reading the implementation or the API documentation.
    Steve McConnell sums it up nicely in Code Complete.
    I posted on it here https://blog.binarymist.net/category/dev-pearls/

    “so don’t be proscriptive about this”
    Again, there are lots of opinions around this.
    This is my opinion.
    If your going to be writing API documentation, it needs to be done on all of the API, not just the entities you think need it.
    When you have an organisation of say 50 developers, some with less experience will think
    “Oh, I understand what’s going on, so I don’t need to document it”.
    Of course the consumer of the API probably won’t.
    Plus if your writing the code, you are already familiar with it, so you may think “Oh, it doesn’t need explaining”.
    Standards are about keeping things uniform.
    Having everybody on the same track.
    Whether they agree with it, has little to do with it.
    There are usually standards I don’t agree with, but because they are standards and everybody is used to them (or should be), and has committed to them, I’m happy to abide by them.
    Unless there is an important reason why we shouldn’t do something other than just personal opinion.

    “documentation is only up to date at the point you write it”
    Yeah, which is why self documenting code is important.
    But, API documentation is different.
    If you have to change the API documentation, then your changing the original intent of the entity.
    In which case it’s a re-write.
    If you are just changing the implementation, then the class or routine will still do what it originally did, it may just do it in a different way.
    In which case the API documentation should still hold true.

    “I don’t know any developer who would take this sort of XML documentation as gospel and all too often I see comments for parameters or methods which have been renamed or removed, but the comment is left behind”
    freeranger:
    Are you pair programming, or at least pair reviewing each others code?
    If you are, you will catch this.
    If you’re not, you should be.
    If your not familiar with Scott Amblers “Cost of change curve” check it out…
    http://www.ambysoft.com/essays/whyAgileWorksFeedback.html
    This hi-lights why these activities are so important for us.
    Since we’ve been religiously code reviewing, I can confidently say our code and API documentation match.
    We’re only human and we do miss things, that’s why we have the safety need of another developer looking over our shoulder.

    As for the comprehensive suite of unit tests.
    These won’t necessarily give you the living documentation your looking for.
    Unless they are driven with the likes of BDD.
    I agree, these are effective in helping to create testable code which in itself helps produce well designed modules.
    Providing they are written before the production code.

    the 3rd party component vendors that don’t take their code documentation seriously give API documentation a bad name.
    It’s not the API documentations fault.
    If I had a choice between a 3rd party component that was like this and one that had good documentation, I’d go with the latter.
    Most times there is a choice.

    “If they are for internal use only and not part of your public API then they won’t (or shouldn’t) appear in any API documentation anyway, so would seem doubly-redundant in this case.”
    What makes you say that?
    Often I’ve come across internal projects that have API’s across an organisations set of teams.
    Those teams that are unfamiliar with the code are glad to have some well written, well maintained API documentation to get them up to speed.
    If it’s not well written, well maintained, I’d take Steve McConnell’s advice and confront the developer (this is how they get better).
    The organisation may not want the assembly to be publicly visible, but definitely want it to be visible to the development teams within the organisation.
    If the internal assembly in question decides it is OK for other assemblies to reference it, then it can explicitly state the other assemblies as friends.

    • freeranger Says:

      Hey binary,

      I think you may misunderstand – I am not against documenting methods, but not every method requires a comment, and not every method/class is an API you are publishing that other teams (or the public) need to understand, and indeed you aren’t always generating chm or documentation files even if it is an API banging made available to others.

      If you prescriptively say that every public/protected/internal method must be documented, you run the danger, which I have seen in every instance where I have worked that this has been the case, that the documentation consists almost entirely of parroting the method and parameter names and little else.
      Yes it meets the “you must document the method” criteria, and indeed it may well be sufficient to describe the method, but then so is the method name and parameters in this case so the comments are wholly unnecessary.

      Document when documentation is warranted and hopefully the documentation you do produce is good quality rather than just quantity. And yes, where you are publishing an API, you are likely to need more of it.

      Incidentally, when I referred to internals not needing documentation since they would not feature in the documentation, I mean an internal method/class not visible outside the assembly, not something that is public which is published internally in your organisation. The need for consumers of your API within the organisation to understand it is no less for internal consumers than external ones.
      Outside the (debatable) practice of allowing test assemblies access to internal methods and classes, I have not come across a situation where an assembly needs to be “public” within a company but not outside of that so perhaps the need is not common enough that you need to prescriptively document internal methods?
      Granted I have not worked for the likes of Microsoft or for a tools vendor where *maybe* this is a common occurrence, but I have been developing for about 20 years, so I have worked in quite a few places….

      Am I pair programming or pair reviewing code? Currently, no, but that’s not my choice – pair anything necessary requires more than one participant and if that is not the culture in your work place, then it’s not likely to happen. I am a contractor and move around on average every 12 months or so. Some places do practice pair programming (to different degrees), others do not. Some places have regular code reviews, some places never have code reviews – though in my experience, where code is reviewed, it is the code that is reviewed, not the comments :}

      Re: unit tests – they test the behaviour of the code under test, so in that sense, they document what happens for input A, result B happens. Granted, unit tests are not always clear (often a sign that more refactoring is required, especially if there is a lot of setup code), but you should br able to have more confidence in them than a comment written .
      Certainly BDD or at least BDD-style descriptive test class and test method names help in understanding the code and acting as “living documentation”

      TBH, I think we are going to have to agree to disagree on this one m8 – but I do agree with most of your standards, and certainly agree that is is more important to have *a* set of standards than a set of standards that you personally wholeheartedly agree with. The standards that work best, IME, are the ones that that team comes up with together rather than being ones imposed upon you – it’s harder to stick to something you’re not invested in, particularly if you have someone to watch over you via pair programming or code reviews.

      BTW, it’s a bit old now, but have you read Microsoft’s Framework Developers Guide? The story behind that (in the intro) is quite interesting in itself – in trying to agree standards, they sometimes found there was no compelling reason to pick A over B (use of _ or not in member variable names for example), but they had to pick *something*. Also, it is interesting where they lay out a standard for something and the reasons behind it, then have a boxed comment from, say, Jeffrey Richter, arguing passionately the exact opposite of said standard. It’s a surprisingly good read.

      Cheers.

      • binarymist Says:

        freeranger:
        Do you have a link for the “Microsoft’s Framework Developers Guide”?
        Is it this one?
        http://msdn.microsoft.com/en-us/library/hh156542(v=vs.110).aspx

        Always keen to hear from other developers experiences.
        Appreciate your comments.

      • freeranger Says:

        This is the book I mean: http://tinyurl.com/framedesguide
        Strangely, although it is written by 2 Microsoft guys, about Microsoft’s own practices, it is published by Addison-Wesley rather than Microsoft Press….go figure

      • binarymist Says:

        Oh. You mean “Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries” rather than “Microsoft’s Framework Developers Guide”?
        That was on of the sources I used when I wrote the “C#.NET Coding Standards and Guidelines”, along with others such as:
        “Coding Guidelines for C# 3.0 and C# 4.0”,
        “C# Coding Standards for .NET by Lance Hunt”,
        “IDesign C# Coding Standard 2.4”,
        “http://msdn.microsoft.com/en-us/library/ms229042.aspx”,
        “http://blogs.msdn.com/b/brada/archive/2005/01/26/361363.aspx”,
        “Code Comlete”,
        “Clean Code”.

        Yeah, well Microsoft Press publish a lot of non Microsoft related materials.

        Cheers.

  7. ucwhyioc Says:

    You can use an extension method to achieve both performance and elegance for the string check.

    public static bool FasterStringIsNullOrEmpty(this string stringToTest)
    {
    return stringToTest == null || stringToTest.Length == 0;
    }
    the good part of the exception handling is missing the exception param passed to the Log method

    Exception logic
    // Bad!
    catch(Exception ex) {
    Log(ex);
    throw ex;
    }

    // Good!
    catch(Exception) {
    Log(ex);
    throw;
    }
    the Good part should be
    catch(Exception ex) {
    Log(ex);//===> avoid a null exception in your exception handling 🙂
    throw;
    }

  8. Darren Sherwood Says:

    >>Place first brace of the block at the end of the line preceded with a space.

    ..I do this for Javascript as it is the convention for that language, for C# it is convention to put the brace on a new line and so I do that.

    • binarymist Says:

      It depends.
      There is no hard and fast rule with this one in C#.
      The people making the decision just need to agree.
      I’ve worked for companies with standards that embrace both ways.
      So it doesn’t matter, but pick one and stick with it.

  9. swapnanair Says:

    Reblogged this on swapnanair and commented:
    Thought this is really helpful for the team

  10. GloryDev Says:

    Generally I agree with these standards but blew up at the don’t user var.
    Dog dog = new Dog();
    seems like it fails the DRY (Don’t repeat yourself) test.
    var dog = new Dog();
    feels better
    also we do a fullon TDD and I have found that my tests are easier to maintain when I use var as my code migrates and as its model becomes clearer the tests stay passing and have less maintenance.

    Also I trust and love resharper 😉

    • binarymist Says:

      @GloryDev
      I don’t see the repetition in your example?
      Dog is a type, dog is an instantiation, new is a key word, Dog() is a constructor.
      Be careful doing things solely based on feelings. They will let you down.
      “when I use var as my code migrates and as its model becomes clearer the tests stay passing”
      Have you considered writing your production code to satisfy your tests rather than the other way around?
      “Also I trust and love resharper”.
      Are you leaning too heavily on your tools?
      They are there to help us, not to write the code for us.
      If your doing everything resharper tells you, you may have some deeper issues.

      • David Clarke Says:

        Are you blind 😉 I think it’s clear the point that GloryDev is trying to make and while it’s a stretch to apply the DRY principle to the example the point is valid. If Dog was a more common generic type with a good descriptive name then using var will save a considerable number of keystrokes without loss of clarity.

        With respect to feelings, I find that I am more frequently let down when I ignore my gut instinct. After all, gut instinct is based on experience and when I look deeper I often find there are good reasons why my feelings are nudging me in a particular direction. YMMV.

        I too like and trust Resharper but I switch off some of Resharper’s recommendations and the OP doesn’t mention following every Resharper recommendation. We all have tools we rely on to help us be more effective at building quality products. Do you write your code in Notepad? I suspect like the majority of C# devs you use Visual Studio. Is it possible to rely too heavily on VS? Absolutely. To use a tired analogy, like any craftsman the tools are important but it is how the tools are used that differentiates the novice from the expert.

  11. How to Increase Software Developer Productivity | Binarymist Says:

    […] I’ve compiled a set of these here: JavaScript Coding Standards and Guidelines Generic Coding Standards and Guidelines C#.NET Coding Standards and Guidelines […]

  12. Adam Crawford Says:

    I agree with you that private member variables should have an underscore prefix, even though my reasoning is slightly different (I believe it provides a quick indicator of where someone has referenced the backing variable for a property rather than accessing the property itself). However, you’ve violated your own standards in the Calling Routines section – these calls are clearly inside a method body but have variables declared with an underscore.
    I’m also with everyone else on the preferred use of var – though my reasoning is that if you have to refactor a method to return a different type that has a similar interface then you don’t need to change the consuming code.

    • Kim Carter Says:

      Thanks and good spotting Adam. Updated. Also added some more info around the reason for the removal of the null check in the Events, Delegates section.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: