C# Best Practices

Writing your programs using C# in Visual Studio assumes you understand the best practices that make your program maintainable and well structured. In this article by Eman Mughal, we get his take on some of the general best practices to make you a better programmer.


  • Simplify your code
    • First point in simplification of your code is that does anyone with 2 or 3 years of experience can understand your code? Depending on experience programmers can write much elegant and beautiful code with in fewer lines but does that code understandable with a person with less experience?
  • Method should only do one thing
    • Normally we write methods those can perform more than one tasks, So its better to split your tasks into smaller sub methods so that each method can do only one task.
  • You should be consistent with your naming conventions.
  • During the construction of your application think about classes and design patterns you can take advantage from.
  • Use properties instead of public variable
    • Properties can give you access methods getters and setters.
    • So by using getter and setters you can have validations in Set method or you can use threading support by using Lock statement in get method. Performance wise they are same but using properties and getters and setter allows your application to be extendable.
  • Use Runtype vs compile time constants
    • Use readonly instead of const keywords. It provide flexibility at runtime while const keyword define constants at compile time. 

Using string

  • Format() or Stringbuilder class
    • String concatenation operations are expensive. When we do concatenation a new copy of string is created in memory.
    • If you are using single concatenation like string + string then its fine. But if you are going to use complex concatenations like, looping through and building complex strings then use string builder class or string.format method.
  • Use String.IsNullOrEmpty
  • Use String.IsNullOrWhiteSpace rather than mannualy checking for null or empty
  • Use Foreach loop instead of index based loops
    • Using foreach loop compiler will generate optimized code
    • Foreach also allows you to work better with collections of particular type. It provides you maintainability. If you want to change the type of collection then maintaining this change is more easy and less error process in foreach loop, but on the other hand if you will write loop with integer counter, in that case, you will need to rewrite the entire loop logic and rewriting loop will open the doors of errors as well. So by using foreach loop it is good practice.
  • User variable initializers instead of initializing variables in contructors
    • Initializer
      • Public class Customer {
      • Private string Name = “Will”;
    • Assignment
      • Public employee() {
      • Name = “Will”;
    • It’s not related to performance it’s related to maintainability issue. So in constructor initialization if you want to add multiple constructors then you need to repeat initialization code in each and every constructor. But if you will initialize your variable right away then you will not need to repeat same initialization code again and again for each constructors. Yes you might be thinking that we can call one initialization constructor from each constructor. That is true, but again there are chances that you might miss, and secondly in case of variable initializer you do not even need to call initialization constructor with each of your other constructors.
  • Casting is one of those things that can get you in trouble
    • Customer customer = (Customer)user;
    • //this can throw an exception
    • If (user is Customer)
      • customer = (user as Customer); //it will return null when exception occurs
    • So in the above example using “is” and “as” will be best practice instead of casting.
  • using” keyword manages object disposal
    • Using (MyClass myclass = new MyClass() ) {
      • //use MyClass
      • } //MyClass is Disposed
    • So above code is more cleaner and elegant instead of calling Dispose() method explicitely.
    • So by in order to use “using” statement you need to implement IDisposable interface with your classes. And then provide the implementation of Dispose method in your classes. By using this technique you can use “Using” statement. Which will automatically call Dispose() method of your class. And In that class you can write code to free external resources like connection objects, streaming object, file handlers etc.

You can read the entire article here.


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