Tag Archives: Extension method

C# Code Guidelines

Coding Guidelines

Every development team or software development team need guidelines to follow to help them write consistent code that keeps maintenance costs low, and development productivity and code reuse high.

I recently updated the ones I use with my team, and though I’d share them to save others having to create their own.  Feel free to reuse in part or full for yourself or your team, and leave a comment with any general suggestions.  Style can be a very personal thing, so don’t be afraid to adapt them to meet your teams own preferences, the key is that all the team follow the same convention, and wherever possible that convention matches the underlying framework you are using.

Naming Conventions


Use PascalCasing for namespaces, types, and member names.

Use camalCasing for local variables, parameters, and user interface fields.

Use camalCasing with an “m_” prefix for private non-user interface fields.

In 3rd Party Templates or code that uses a “_” prefix within a class rather than a “m_” prefix then be consistant within the class and either rename all to “m_” or continue with the “_” prefix.

Type Notations in Variable Names

Hugarian Notion must not be used – When the type is an important part of the variable’s purpose include it in the name by prefixing or postfixing it to the name without abbreviation.

Do not use abbreviations – If an acronym is widely accepted and used in the framework or toolkit being referenced then it acronym may be used despite the rule to avoid abbreviations.

.NET Word Conventions

Following .NET conventions for the words:

  1. Indexes (not Indices)
  2. UserName (not Username)

Use the following symmetric words when defining pairs of functionality:

  1. Add / Remove
  2. Insert / Delete
  3. Create / Destroy
  4. Initialize / Finalize
  5. Get / Set
  6. LogOn / LogOff
  7. Begin / End
  8. Register / Unregister

Use the following American words rather than the British words for member names:

  1. Color
  2. Initialize

Use of Plural and Singular Words

Name all classes with a singular word or phrase.

Name all collections or with plural words or phrases.

Name all namespaces as plural words or phrases unless the namespace has a special meaning in the MVC framework.

Compatibility with COM and other CLR Languages

Do not name two public or protected members with names that are the same excluding character case.  This would prevent reuse of the classes in languages such as VB.NET.

When an argument for a class is passed in to a method or constructor with the purpose of setting the public member, then use of the same name in camelCase rather than PascalCase is recommend over prefixes or suffixes.


Name all static singletons that initialise themselves “Default” unless there is a specific reason to use another name.

Name all static singletons that do not self-initialise “Current” unless there is a specific reason to use another name.

Simple Names

The following simple names are allowed for the uses specified:

  1. obj – to store a generic object who’s type is unimportant.
  2. i, j, k – for control of loops.
  3. s – to store a string value of a variable already in scope in a different type.
  4. e, ea, ee – for subclasses of EventArgs.
  5. e, ex – for subclasses of Exception.
  6. item, it – for the control variable in LINQ query expressions.

Use of Types in Variable Declarations

Use the most specific type available in a variable declaration that is not initialised in-line.

Use var for types that are initialised in-line.

Do not use var for types that are initialised in-line to values of a standard type (e.g. int, string, decimal etc.).

Use var for variables that are initialised as the result of method calls that return collections.

Use var for variables that are storing anonymous types.

Use var when the exact type of a variables is unimportant to the method as more than a return value from an invocation.

Use object for types that are initialised as the result of method calls where the return type is going to be worked with only via reflection.

Use interfaces for variable types if the work being done is dependent only on the interface.

Use dynamic as a variable type only if the type could not be known at compile time, and the code is not going to reflect on the type.


Constructor Performance

Avoid use of database connections in constructors.

Avoid use of network calls in constructors.

User Interface Design Time Requirements

Constructors for User Interface classes must be design time compatible.

Member Initialisation

Do not add constructor overloads that perform member initialisation as part of its parameters, these should now be handled by the member initialisation syntax.

Factory and Dependency Injection

Provide a zero parameter constructor unless the class is entirely unusable without a parameter.

Ensure the zero parameter constructor is suitable for use in a class factory or service locator.

Ensure the zero parameter constructor is suitable for use in dependency injection.

Ensure constructors do not over initialise to prevent subclasses from changing implementation details.

Virtual Calls

Avoid calling virtual members from constructors as the behaviour is unpredictable.

Static Constructors


Avoid initialising static members within static constructors.

Wherever possible initialise static members on first use.

Asynchronous Code

Use the await and async keywords when creating asynchronous code.

Prefix “Async” onto all methods that need to be awaited.

Do not prefix “Async” onto any method that cannot be awaited, even if the method contains asynchronous code.

When blocking methods are part of a Portable Class Library and cannot use the await and async keywords, use extension methods with the “Async” prefix to provide asynchronous alternatives for platforms that support it.

When to use Properties, Methods, and Extension Methods


Use a property if:

  1. The functionality behaves like a field.
  2. Is a logical attribute of the type.
  3. Is unlikely to throw exceptions.
  4. The contained code has minimum value when debugging.
  5. Does not have a dependency on the order being set.

Never use a property if:

  1. A get implementation is not provided.


Use a method if:

  1. The operation is a conversion.
  2. There is an observable side-effect from the call.
  3. The order of execution is important.
  4. The method may not return.
  5. The method may run code asynchronously.
  6. The result should be cached for reuse within the calling method for performance.

Do not use a method if:

  1. The return value is a collection that remains linked to the instance.

Extension Methods

Use an extension method if:

  1. The operation needs extend a sealed type.
  2. The operation needs to apply to anonymous types.
  3. The operation needs to apply to general IEnumerable types.
  4. Base functionality is provided for an Interface.

Do not use extension methods if:

  1. The behaviour may want to be specialised by a base class.

Place extension methods that form part of a classes or interfaces core API, or platform specific extensions to the core API, in the same namespace as the class, even if it is provided by another assembly.

Always place extension methods that extend core .NET types outside of the System.Collections namespace in a namespace ending in “.Extensions” to avoid littering the namespace of these core objects.

Method Arguments

Name method arguments with names that inform the caller of the intended purpose, not of its internal use.

When a Boolean argument is used as a flag to change fundamental functionality of a method, always call it using the “name: true” style.

Use Boolean arguments called with the “name: true” instead of two member enumerators for all methods, unless the method extends an API where an existing enumerator is better suited.


Catching Exceptions

Only catch exceptions of specific types if the error message being returned will be specialised for the type.

Catch the generic Exception type to isolate calls from the calling code.

A user must be informed of an exception with an error or warning message.

An error or warning message can be omitted if an exception is caught and ignored to avoid a known framework or platform issue and the issue is commented within the catch block.

Do not catch the general Exception type and hide its value from the user.

Throwing Exceptions

Use the existing Exception types to throw your own exceptions.

Only create Exception subclasses when they are to be used multiple times within a library.

LINQ, for, and foreach.

Use LINQ for queries to external data sources.

Use LINQ for queries over in memory data that is designed for use as a dictionary or database.

Use foreach () for iterating over any IEnumerable.

Use var as the item type for the foreach() loop whenever the IEnumerable implements IEnumerable<T>.

Use for() when the iteration is controlled by a numeric block.

Use for() to walk hierarchies.

Use for() or while() when the iteration is controlled by a non-numeric exit condition.

Use do { } while () only where it reduces code compared to a for() or while().


Member Comments

Every public member or class must be commented with an XML comment.

Every protected method and property must be commented.

The comment must be written to explain why somebody would want to invoke the code.

The comment must not be a substitute for a bad member name.

The comment should not attempt to list all exceptions that could be thrown but should exceptions of special Exception subclasses thrown directly by the code.

Do not comment private or internal methods that have obvious use.

Do not comment event handlers unless their implementation is non-obvious.

Ensure member comments are suitable for extraction into API documentation.

Do not repeat the XML comment for overridden methods if the comment has nothing new to add to the base type comment.

Do not repeat the XML comment for the implementation of a member for an interface if the comment has nothing new to add to the interface member comment.

Code Block Comments

Comment code with headers within blocks that perform multiple tasks discrete as part of its implementation.

Comment code blocks that cannot be understood by the code alone.

Comment code wherever a special or magic value is used.

Comment code when a condition in a control block could be misunderstood.

Comment Styles

Use /// Comments when commenting members or classes.

Use // Comments when commenting code blocks or statements

Use /* */ comments only if the comment has to be placed in the middle of a line of code or within a Razor syntax document.

Special Developer Comments

Always mark comments that are reminders of code to fix with “TODO” in upper case followed by a message.  This allows all TODO items to be found and completed or before the release of any solution.

If the last statement of a non-void method is not a return statement, place the lint style comment “/* NOTREACHED */ at the bottom of the method so developers know to maintain this when editing the code.

Braces and Brackets

Brace Positioning

Place opening braces for classes, namespaces, and members on new lines.

Place opening braces for code blocks such as if, for, foreach, while, do, and switch on the same line as the code control statement.

Place all closing braces on new lines.

Place both the opening and closing braces for automatic properties on the same line as the property name e.g. public int MyProperty { get; set; }

Place both the opening and closing braces for anonymous types used as property bags on the same line e.g. Html.Link(“Test”, new { this = “that” })

Place else and else if statements on the same line as the closing brace and keep the next opening brace on the same line too.

Bracket Positioning

Place a space between keywords such as if, for, foreach, and while, and the opening bracket.

Do not place a space between a method name and its opening bracket.

Keep the closing bracket on the same line as the opening bracket in the argument list is small.

If the argument list for a method call is long: keep the opening bracket on the same line as the method name, place each argument on a separate line ending with a comma, and place the closing bracket on a new line.


If like me you’ve worked with C# and the .NET framework for years then you will probably have written variations on following code hundreds of time when trying to display values on screen or save values into text based files or SQL statements:

object rawValue = SomeMethodCall();
string displayValue = String.Empty;
if (rawValue != null) {
    displayValue = rawValue.ToString();

The code itself is simple enough to get right first time, and easy to read and understand, but after you’ve written it a few dozen times it starts to appear like unwelcome rash across your code. A programmers next natural instinct is to see if there is a way to shorten the code.

Unfortunately the ?? operator can’t help us here unless we are exclusively dealing with strings for rawValue (in which case why are you calling ToString()?). We can however shorten things substantially with the ? operator:

object rawValue = SomeMethodCall();
string displayValue = (rawValue == null? String.Empty: rawValue.ToString());

This has helped and taken our code from five lines to two, and hasn’t noticeably affected readability. But if we are only interested in the displayValue woundn’t it be nicer if we were able to just do:

string displayValue = SomeMethodCall().ToString();

This code will execute fine, but as soon as a null object is returned from SomeMethodCall() we’ll get a NullReferenceException raised and if we didn’t see it in testing, our end users will see an unhandled exception we should never have introduced.

If we try to use the ? operator directly with the method call and the best you can get is:

string displayValue = SomeMethodCall() == null? String.Empty: SomeMethodCall();

You can tell immediately from the code that this would be at best wasteful if not potentially damaging depending on the side effects of SomeMethodCall(). Under normal circumstances, where SomeMethodCall() doesn’t return null, we end up executing SomeMethodCall() twice. If the method accesses a web service or database we will have potentially doubled the impact of the code on the server, and slowed down the user experience.

What can be done then? Should we just put up with the two line of code where one would work? Until recently I would have said yes, but with LINQ usage on the rise I’ve started to see this particular problem causing ugly code to be written for lambda statements, or worse developers knowingly being lazy with their handling of potential null values when calling .ToString()!

We can actually use a little used feature of extension methods to help us with this problem. As you will know extension methods allow us to invoke static utility methods in a syntax that mirrors invoking a member of a class. The compiler understands the code that calls an extension method and effectively re-writes the syntax from a member call to a static method call for us. To get an idea of how this works take a look at my previous post.

Because the member-like syntax is converted into a static method call, it is possible to call the member on a null reference.  Therefore the first line of the following code would throw a NullReferenceException, but if MyExtensionMethod() was an extension method that handled a null specially, the second will not.


Using this technique we are able to create extension methods that special case null values, but maintain the readable member-style syntax.

I’m going to throw a strong word of warning in here now. When you add an extension method that does not behave like a member method call, particularly ones that don’t raise a NullReferenceException when called on a null variable you are moving away from basics that programmers take for granted when reading code. Used incorrectly this can make code harder to understand and therefore harder to understand. You should be sure about what you are doing before you add extension methods that expose this non-standard behaviour. Its been my experience that methods that should follow this behaviour are almost always involved with displaying values as strings, or converting values between types to pass to an ORM or similar module.

My personal convention to make sure I can identify where the technique has been used is to suffix the method name with “Safe”, so the call above would be MyExtensionMethodSafe(). If everybody in the team follows this convention when they feel there is a genuine need for the extension method to treat nulls differently to a member method call then the code remains easy to read. Don’t forget however that even if you’ve adopted this convention throughout your team, you will still have to train new people joining the team on the convention.

Now with that warning having been strongly stated, lets return to looking at the problem at hand. In this case I believe it makes very good sense to provide a “Safe” extension method companion to ToString(). Here is the code for the ToStringSafe() extension method in full:

namespace Mvpc.Extensions
    public static class ObjectExtensions_ToStringSafe
        public static string ToStringSafe(this object value)
            // Nulls just return empty strings.
            if (value == null) {
                return String.Empty;

            return value.ToString();

If you read my post on async extension methods you will already know that I recommend placing any extension method that works on string, object, int, or any of the core types of the .NET Framework under a namespace ending in “Extensions” so they don’t litter the initilisense when the user doesn’t need them. This rule applies here too as the majority of code will not want to use the ToStringSafe() method.

After adding a using for the Mvpc.Extensions namespace it finally becomes simple to write:

string displayValue = SomeMethodCall().ToStringSafe();

We finally get our five lines of oft-duplicated code down to a single readable line.

Since introducing this new method I’ve completely stopped seeing programmers being lazy with their .ToString() handling of nulls inside lambda statements. Hopefully you will see the same too as well as being able to produce more readable null-safe code.

Async extension method wrappers

Asynchronous APIs are becoming more popular thanks in part to the focus on asynchronous user interface design requirements on platforms such as Windows Store Applications for Windows 8 and Windows RT.

This attempt to change the way developers think about long or unpredictable operations is welcome and necessary as databases and files slowly migrate into the cloud.

Unfortunately System.Threading.Tasks and the async and await keywords are not available inside portable class libraries or some of the platforms we target with the Ambidect technology.  We could choose to use an alternative style of asynchronous API, such as call backs, but these are starting to look dated, and require the developer to do a lot more boilerplate work to use.

At this point you may be tempted to give up and provide only an blocking synchronous API and require the developer to manage their own threads on each platform that insists on asynchronous calls; but as I touched on in my previous post about the repository API, we felt it was a much better idea to provide an async API and did so using extension methods.

This technique can be used to wrap almost any synchronous API; but I have to stress at this stage it should only be used if the platform or platforms you are working on do not have a usable native asynchronous API.

For our example we’ll work with the Find method of the IRepository<> interface, but the principles here will work with any synchronous call that needs to be wrapped.

The first thing we need to do is create class to host our extension methods:

using System;
using System.Threading.Tasks;

namespace Mvpc
    public static class IRepositoryExensions_Async
        // TODO this is where to put your extension method code.

If you are not familiar with extension methods, the reason we mark the class as static is because its a requirement of the extension method support of the compiler.  The name of the class can be anything you want, but you can see that I use a simple convention that makes it clear to anybody using the library that the class contains extension methods, so is of no interest to be used directly.

You will note that the class here has been put into the Mvpc namespace to go alongside the class we are wrapping.  When using extension methods that extend the API with asynchronous members this is my recommended approach.  It stops the developer of the class worrying about how the async methods are provided, and intilisense will include them in the list of available class members when working on a platform that supports our asynchronous API.

In cases where the extension methods provide utility functions rather than a core API for a class, it is good practice to keep your extension methods in a separate namespace, e.g. Mvpc.Extensions.  This stops the intilisense list being over-populated with extension methods that are not relevant to the code at hand.  When extending one of the CLRs core types such as object or string I always insist that the extension method goes into a namespace ending in “Extensions” such as Mvpc.Extensions that the developer has to explicitly opt into.  This not only helps keeps the intilisense clean, but also stops accidental dependencies on the specific extension methods creaping into code blocks where they don’t belong.

Now we have a class setup and have decided the right namespace for the class lets add an extension method.  An extension method is exactly the same as a normal static method, except its first parameter is prefixed with the “this” keyword.  This instruction tells the compiler that it can effectively rewrite the extension method call into a static method call, while allowing the developer using the extension method to use a more natural calling convention.  For example instead of having to call:

var repository = ...;
var key = Guid.NewGuid();
IRepositoryBaseExtensions_Async.FindAsync(repository, key);

We can use the much more readable:

var repository = ...;
var key = Guid.NewGuid();

Lets have a look at the code for the FindAsync() extension method itself now:

        public async static Task FindAsync(this IRepository repository, params Guid[] keys)
            var task = System.Threading.Tasks.Task.Factory.StartNew(() =>
                var ret = repository.Find(keys);
                return ret;

            return await task;

The first thing you will note is that we suffix the name of the method with “Async” I find this a very good convention to follow for any method that provides an async API that can have “await” applied to it. It helps the person using the method remember that at some point they will likely want to await on the result.

If you are unfamiliar with the async and await keywords I suggest you have a look at them in the MSDN documentation sufficient to say here that you use async to mark a method as containing asynchronous code, and await to safely wait for the result of an async method before continuing.

As well as the async keyword you will notice the method is also marked as static as it will operate without a class instance and the first parameter is prefixed with “this” keyword to enable the extension method style shorthand call to the method.  We can still call the static method directly if we want, but without the “this” keyword the extension method syntax would not be available when calling the method.

Inside the method we create a new Task with the right return type and use an lambda expression to perform a call to the synchronous API we are wrapping.  This code will be executed in a separate thread before returning its result.  Exactly when the code pauses to wait for the result depends on how we use await when calling the extension method.

More often that not when we will want the code to wait for the value before continuing so we will use await directly on the async call as follows:

var repository = ...;
var key = Guid.NewGuid();
var item = await repository.FindAsync(key);

In this post we’ve wrapped a synchronous call to a repository function with an async extension method, but you can use the technique whenever you find you need to make regular asynchronous calls to a class that couldn’t be built with an asynchronous API, or to which you do not have access to the source to extend with a native asynchronous API yourself.

OfType() and Cast() with System.Type instead of Generics

We all know that whenever possible we code should be written to be type safe. But there are times when its simply not possible. Once such time we came across when putting together the Mvpc libraries behind the Ambidect Technology involved working with Cast<>() and OfType<>() with IEnumerables of unknown types.

Working with collections of known types is as simple:

var myCollection = collection.Cast();
var myCollection2 = collection.OfType();

But what do you do when all you have is a System.Type?  Sure you can try and avoid the situation but sometimes it really is bad design for the code to know the element when all it cares about is the fact we have an IEnumerable.  Yet other times the type may not even exist until it is emitted at runtime either by ourselves, or by a Json or similar library wrapping a web service.

Thanks to reflection it is possible to implement Cast(Type type) and OfType(Type type) in a cross platform way and cope with these cases when they arise.

The first thing we need is a normal generic method we can call. For Cast<>() we can define it as follows:

        private static IEnumerable CastInternal(System.Collections.IEnumerable source)
            return source.Cast();

Nothing noteworthy in that code. Now we just need a method we can pass a System.Type to. First the code then we’ll take it line by line:

        public static System.Collections.IEnumerable Cast(this System.Collections.IEnumerable source, Type elementType)
            var methodTemplate = typeof(IEnumerableExtensions_UntypedCasts).GetMethod("CastInternal", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
            var genericMethod = methodTemplate.MakeGenericMethod(elementType);
            return (System.Collections.IEnumerable)genericMethod.Invoke(null, new[] { source });

This code can look very confusing if you haven’t used the System.Reflection namespace before but its actually very simple.

Line 2 uses reflection on the current type and gets the CastInternal() method we defined in the previous code block. (In the example code we’ve wrapped the extension method in a static class called IEnumerableExtensions_UntypedCasts. You will need to change the type name if you add the code to a class with a different name). At this point the MethodInfo doesn’t point to a method we can call, but a generic definition.

Line 3 uses that generic definition to create a method that can actually be called. No use of the System.Reflection.Emit namespace here so the code will run on all platforms, even those that don’t support dynamic code execution. It also means we can keep it contained in a Portable Class Library.

Line 4 invokes the newly generated method and simply returns its value.

If you add these extension methods to a static class in your own code you can then call Cast() on an IEnumerable when all you have is a System.Type of the target element type:

var type = typeof(MyType);
var collection = originalCollection.Cast(type);

The definition of OfType(System.Type) is exactly the same with the Cast<>() method swapped for OfType<>().

Hope you find them useful for those situations where you simply can’t or shouldn’t know the element type until runtime.