Don’t and Do’s in C#

For a while now I have been reviewing developers code and performing code reviews and I have noticed some common mistakes are being repeated time and time again. These are mostly the mistakes, which once you point them, are quite easy to remember. However, if a developer is not aware of them, they can cause many problems with the efficiency and quality of the developed software. So what are these common mistakes and why are they wrong?

String concatenation instead of StringBuilder

String concatenation works in such a way that every time when you add something to a string, a new address in the memory is being allocated. The previous string is copied to a new location with the newly added part. This is inefficient. On the other hand we have StringBuilder which keeps the same position in the memory without performing the copy operation. Thanks to the strings’ appending by means of StringBuilder the process is much more efficient, especially in case of hundreds of append operations.

//Just wrong
List values = new List(){"This ","is ","Sparta ","!"};
string outputValue = string.Empty;
foreach (var value in values)
   outputValue += value;
StringBuilder outputValueBuilder = new StringBuilder();
foreach (var value in values)

LINQ – ‘Where’ with ‘First’ instead of FirstOrDefault

A lot of programmers find a certain set of elements by means of ‘Where’ and then return the first occurrence. This is inappropriate, because the ‘First’ method can be also applied with the ‘Where’ condition. What’s more, it shouldn’t be taken for granted that the value will always be found. If “First” is used when no value is found, an exception will be thrown. Thus, it’s better to use FirstOrDefault instead. When using FirstOrDefault, if no value has been found, the default value for this type will be returned and no exception will be thrown.

List numbers = new List(){1,4,5,9,11,15,20,21,25,34,55};
return numbers.Where(x => Fibonacci.IsInFibonacciSequence(x)).First();
/Almost correct
return numbers.First(x => Fibonacci.IsInFibonacciSequence(x));
return numbers.FirstOrDefault(x => Fibonacci.IsInFibonacciSequence(x));

Casting by means of ‘(T)’ instead of ‘as (T)’ when possibly not castable

It’s common that software developers use simple ‘(T)’ casting, instead of ‘as (T)’. And usually it doesn’t have any negative influence because casted objects are always castable. Yet, if there is even a very slight probability that an object can be under some circumstances not castable, „as (T)” casting should be used. See Difference Between C# Cast Syntax and the AS Operators for more details.

var woman = (Woman)person;
var woman = person as Woman;

Not using mapping for rewriting properties

There are a lot of ready and very powerful C# mappers (e.g. AutoMapper). If a few lines of code are simply connected with rewriting properties, it’s definitely a place for a mapper. Even if some properties aren’t directly copied but some additional logic is performed, using a mapper is still a good choice (mappers enable defining the rules of rewriting properties to a big extend).

Incorrect exceptions re-throwing

C# programmers usually forget that when they throw an exception using „throw ex” they loose the stack trace, how many times have I seen this? It is then considerably harder to debug an application and to achieve appropriate log messages. When simply using „throw” no data is lost and the whole exception together with the stack trace can be easily retrieved.

//So So wrong
   //some code that can throw exception [...]
catch (Exception ex)
   //some exception logic [...]
   throw ex;
   //some code that can throw exception [...]
catch (Exception ex)
   //some exception logic [...]

Not using ‘using’ for objects disposal

Many C# software developers don’t even know that ‘using’ keyword is not only used as a directive for adding namespaces, but also for disposing objects. If you know that a certain object should be disposed after performing some operations, always use the ‘using’ statement to make sure that the object will actually be disposed.

//the below code:
using(SomeDisposableClass someDisposableObject = new SomeDisposableClass())
//does the same as:
SomeDisposableClass someDisposableObject = new SomeDisposableClass();

Using ‘foreach’ instead of ‘for’ for anything else than collections

Remember that if you want to iterate through anything that is not a collection (so through e.g. an array), using the ‘for’ loop is much more efficient than using the ‘foreach’ loop. See Foreach vs For Performance for more details.

Retrieving or saving data to DB in more than 1 call

This is a very common mistake, especially among junior developers and especially when using ORMs like Entity Framework or NHibernate. Every DB call consumes some amount of time and therefore it’s crucial to decrease the amount of DB calls as much as possible. There are many ways to do so:

  • Using fetching (Eager Loading)
  • Enclosing DB operations in transactions
  • In case of a really complex logic, just moving it to the DB by building a stored procedure
With any SQL connections you can always use the SQL Profiler to see what is happening, and it is quite often easy to spot the excessive use of database connections and more so repeated tries of the same routine.
Just a few I know, but the more common mistakes that developer make when programming day to day.

Visual C# and .NET 4.0 samples

I came across some nice C# samples from Microsoft today providing everything from Hello World, to how to use Yield and how to program Attributes.

Official Visual Studio 2010 Samples for C# 4.0

Worth having a look at if you are a beginner or a seasoned programmer.

Language Samples

The C# 4.0-specific samples are called:

  • Named and Optional
  • Office Sample
  • Python Sample
  • Simple Variance.

Here is the complete list of language samples:

  • Anonymous Delegates: Demonstrates the use of unnamed delegates to reduce application complexity.
  • Arrays: Shows how to use arrays.
  • Attributes: Shows how to create custom attribute classes, use them in code, and query them through reflection.
  • Collection Classes: Shows how to make non-generic collection classes that can be used with the foreach statement.
  • COM Interop Part I: Shows how to use C# to interoperate with COM objects.
  • COM Interop Part II: Shows how to a use a C# server together with a C++ COM client.
  • Commandline: Demonstrates simple command-line processing and array indexing.
  • Condiational Methods: Demonstrates conditional methods, which provide a powerful mechanism by which calls to methods can be included or omitted depending on whether a symbol is defined.
  • Delegates: Shows how delegates are declared, mapped to static and instance methods, and combined into multicast delegates.
  • Events: Shows how to declare, invoke, and configure events in C#.
  • Explicit Interface: Demonstrates how to explicitly implement interface members and how to access those members from interface instances.
  • Generics: Shows how to make generic collection classes that can be used with the foreach statement.
  • Hello World: A Hello World application.
  • Indexers Part I: Shows how C# classes can declare indexers to provide array-like access to objects.
  • Indexers Part II: Shows how to implement a class that uses indexed properties. Indexed properties enable you to use a class that represents an array-like collection.
  • Libraries: Shows how to use compiler options to create a DLL from multiple source files; also, how to use the library in other programs
  • Named and Optional (C# 4.0): Demonstrates Named and Optional parameters, an alternative to method overloads
  • Nullable: Demonstrates value types, such as double and bool, that can be set to null
  • Office Sample (C# 4.0): Demonstrates how Dynamic and COM Interop make it easy to call Microsoft Office in C# 4.0
  • OLEDB: Demonstrates how to use a Microsoft Access database from C# by creating a dataset and adding tables to it.
  • Operator Overloading: Shows how user-defined classes can overload operators
  • Partial Types: Demonstrates how classes and structures can be defined in multiple C# source-code files
  • PInvokeShows how to call exported DLL functions from C#
  • Properties: Shows how properties are declared and used; also demonstrates abstract properties
  • Python Sample (C# 4.0): Learn how to call a Python script by using the Dynamic feature in C# 4.0
  • Security: Discusses .NET Framework security and shows two ways to modify security permissions in C#: using permission classes and permission attributes
  • Simple Variance (C# 4.0): See how Covariance and Contravariance are supported in generic interfaces and delegates
  • Structs: Shows how to use structs in C#.
  • Threading: Demonstrates various thread activities such as creating and executing a thread, synchronizing threads, interacting between threads, and using a thread pool
  • Unsafe: Shows how to use unmanaged code (code that uses pointers) in C#
  • User Conversions: Shows how to define conversions to and from user-defined types
  • Versioning: Demonstrates versioning in C# by using the override and new keywords
  • XML Documents: Shows how to document code by using XML
  • Yield: Demonstrates how to use the yield keyword to filter items in a collection


These samples help you learn LINQ quickly. They also act as a reference and guide for those with existing LINQ experience. A few handy utilities are also included. They are available in the LinqSamples folder.

  • DynamicQuery: Code to create LINQ queries at run time.
  • LinqToNorthwind: A basic example of how to use LINQ To SQL to query a database
  • LinqToXmlDataBinding: Bind LINQ to XML code to WPF controls
  • ObjectDumper: A utility for writing the output from a LINQ query to the screen in text mode
  • PasteXmlAsLinq: A Visual Studio addin that automatically converts XML to LINQ to XML.
  • QueryVisualizer: Allows LINQ to SQL developers to see the SQL for their query, and also to see the results of the query in a grid.
  • Reflector: Use LINQ to right queries against the objects in your code using the Reflection APIs
  • RSS: This sample acts as a tiny web server that aggregates several RSS feeds
  • SampleQueries: This is the most important sample and contains about 500 examples of how to use each of the query operators in LINQ to Objects, LINQ to SQL, LINQ to XML and LINQ to DataSet.
  • SimpleLambdas: Several examples of how to write and use lambda expressions
  • SimpleLinqToObjects: The hello world of the LINQ samples. This shows you how easy it is to do simple queries of in-memory objects using LINQ to Objects.
  • SimpleLinqToXml: Get started using LINQ to XML.
  • WebServiceLinqProvider(TerraService): A custom LINQ provider and client for the TerraServer-USA Web service.
  • Whitepapers: The following papers are stored in this directory in Word format:
    • LINQ Project Overview
    • LINQ to SQL Overview for C# and VB
    • Standard Query Operators
    • LINQ to XML Overview
  • WinFormsDataBinding: Learn how to display LINQ queries with grids in a Windows form. It includes a one to many query example.
  • XQuery: Another simple LINQ to XML sample query. This sample shows the minimal code necessary to write a LINQ to XML query

Workflow with TFS

I’ve been working with TFS for sometime and when you are using the process flows you need to understand how the workflows work with the work items types.

There are two main types I have worked with Agile and CMMI Process Improvements.

I’m not an expert on these workflows but you can get access to the full guidance from:

The diagrams below are taken from VSTS blog site, but you must remember thes eare just starting points and they can be changed to suit your own workflow within your business

MSF for Agile Software Development

featuring 5 work item types: Bug, Requirement, Quality of Service Requirement (QoS), Risk and Task.

Work Item Type: Bug


Work Item Type: Scenario


Work Item Type: Quality of Service Requirement (also known as “technical requirement”)


Work Item Type: Risk


Work Item Type: Task


MSF for CMMI Process Improvement

featuring 7 work item types: Bug, Requirement, Change Request, Issue, Review, Risk, Task

Work Item Type: Bug


Work Item Type: Requirement


Work Item Type: Change Request


Work Item Type: Issue


Work Item Type: Review


Work Item Type: Risk


Work Item Type: Task

Lifestyles of the Castle Windsor IoC Containers

It’s worth knowing how the Castle Windsor IoC work, by default it uses Singletons, where this will work for the most of the time, there are a lot more options available to you depending on your needs.  These lifestyles that are available in Castle Windsor are:

  • Singleton: components are instantiated once, and shared between all clients
  • Transient: components are created on demand
  • PerWebRequest: components are created once per Http Request
  • Thread: components have a unique instance per thread
  • Pooled: Optimization of transient components that keeps instance in a pool instead of always creating them
  • Custom: allows you to specify a custom lifestyle… you’d have to specify a type that implements the ILifeStyleManager interface

For further information on this take a look at Castle Windsors Lifestyles or  Windsor and component instance lifetimes

Introduction to Dependency Injection

Dependency Injection (DI) is an incredibly useful and easy technique which makes your code a lot easier to test.

I like to use samples to explain Dependency Injection. We’ll use a SqlMetaDataProvider class which needs to provide the meta data coming from a SQL Server database. It retrieves the meta data from the database in a relational structure (a DataSet) and then converts it to an easy to use object model. Obviously, i want to be able to test this class without actually going to the database because that would make the tests slow. So how can we test if the relational data is being converted to the object model without going to the database?

Well, let’s look at what the class does. First of all, it retrieves sql server meta data. Then it converts it to an object model. But retrieving the meta data doesn’t really belong here… it should be functionality that’s offered by another class. So we create a SqlDataRetriever class. All it will do is return meta data in the relational structure. Nothing more. So now, our SqlMetaDataProvider class can simply use the SqlDataRetriever class to retrieve the meta data. So basically, SqlDataRetriever is now a dependency of the SqlMetaDataProvider class because SqlMetaDataProvider is depending on SqlDataRetriever to return the relational meta data.

At this point, our class could look like this:

    public class SqlMetaDataProvider : IMetaDataProvider
        private readonly string _connectionString;
        private readonly SqlDataRetriever _sqlDataRetriever;
        public SqlMetaDataProvider(string connectionString)
            _connectionString = connectionString;
            _sqlDataRetriever = new SqlDataRetriever();
        public MetaDataStore GetMetaDataStore()
            SqlMetaData sqlMetaData = _sqlDataRetriever.GetMetaData(_connectionString);
            return ConvertToMetaDataStore(sqlMetaData);
        private MetaDataStore ConvertToMetaDataStore(SqlMetaData sqlMetaData)
            MetaDataStore store = new MetaDataStore();
            AddTablesToStore(sqlMetaData.TableInfo, store);
            AddColumnsToTablesInStore(sqlMetaData.ColumnInfo, store);
            CreateRelationshipsBetweenTables(sqlMetaData.RelationshipInfo, store);
            return store;

Note: I left out the code for the AddTablesToStore, AddColumnsToTablesInStore and CreateRelationshipsBetweenTables methods because they aren’t relevant to this specific topic.

Now we need to make sure we can replace the instance of SqlDataRetriever during testing with one we can supply ourselves. That test instance could then simply return a DataSet that was created in-memory, thus keeping our tests running fast. Notice how SqlMetaDataProvider has a reference of the type SqlDataRetriever. The type is essentially fixed, which creates a strong dependency on the SqlDataRetriever class. If we were to replace the type of the reference with an interface, it would at least make it easier to use another type for our required dependency, one that simply implements the interface.

So we create the ISqlDataRetriever interface:

    public interface ISqlDataRetriever
        SqlMetaData GetMetaData(string connectionString);

And then we modify the definition of SqlDataRetriever to implement the interface:

    public class SqlDataRetriever : ISqlDataRetriever

Now we need to modify our SqlMetaDataProvider class so it holds a reference to the interface type, instead of the class type:

        private readonly ISqlDataRetriever _sqlDataRetriever;

We still need to find a way to inject our dependency into our SqlMetaDataProvider so we’ll modify the constructor:

        public SqlMetaDataProvider(string connectionString, ISqlDataRetriever sqlDataRetriever)
            _connectionString = connectionString;
            _sqlDataRetriever = sqlDataRetriever;

The only downside to this is that it now takes more work to create an instance of SqlMetaDataProvider… work that clients shouldn’t need to do if they just want to use the default ISqlDataRetriever implementation. If you’re using an Inversion Of Control (IoC) container, you can simply request an instance of SqlMetaDataProvider and the IoC container would also create the necessary dependency for you. Using an IoC container however is outside of the scope for this post, so we won’t do that. In fact, if you know that your production code will always use the SqlDataRetriever implementation, you could also provide a simpler constructor which takes care of that for you:

        public SqlMetaDataProvider(string connectionString)
            : this(connectionString, new SqlDataRetriever()) {}

So you could use the simpler constructor in your production code, and the other one in your test code. Speaking of test code, we still need to write that test which tests the conversion without hitting the database. First, we need to create an implementation of ISqlDataRetriever which allows us to pass a DataSet to it which the ISqlDataRetriever instance should return to its consumer (our SqlMetaDataProvider):

    public class SqlDataProviderStub : ISqlDataRetriever
        private SqlMetaData _sqlMetaData;
        public SqlMetaData SqlMetaData
            set { _sqlMetaData = value; }
        SqlMetaData ISqlDataRetriever.GetMetaData(string connectionString)
            return _sqlMetaData;

And finally, the test:

        public void GetMetaDataStore_ProvideDataSetWithTwoTablesAndRelationship_MetaDataStoreIsCorrect()
            SqlMetaData sqlMetaData = PrepareMetaDataSetInMemoryWithTestData();
            SqlDataProviderStub sqlDataProvider = new SqlDataProviderStub();
            sqlDataProvider.SqlMetaData = sqlMetaData;
            // pass null as the connectionString, and pass our SqlDataProviderStub
            IMetaDataProvider metaDataProvider = new SqlMetaDataProvider(null, sqlDataProvider);
            MetaDataStore store = metaDataProvider.GetMetaDataStore();
Original article by Davy Brion

StructureMap Example

After using StructureMap for a while I thought it would be nice to generate a simple example of how it all works, so I’ve built in Visual Studio 2008, both C# and a VB.NET version.

StructreMap (4.47 kb) (9.41 kb)

For more information on StructureMap please go to their main website

If you need to know more about IoC’s then it’s worth making a look at the following links:

Inversion of Control

List of .NET Dependency Injection Containers (IOC)

IoC Benchmarks

MVC Storefront: Dependency Injection