Monday, February 28, 2011

Some Useful Features of C#

Introduction
In this article, I am going to discuss some important facts which might be unknown to most developers. I am going to discuss about three different topics which are related to C# and are more helpful when building your application.

  • Why use StringBuilder over String to get better performance
  • Structure initialization in C#
  • Checked operator
  • Go To with Switch... Case
I am going to discuss the above list one by one.

Why use StringBuilder over String to get better performance

There are a number of articles and posts that say that StringBuilder is more efficient because it contains a mutable string buffer. .NET Strings are immutable, which is the reason why a new String object is created every time we alter it (insert, append, remove, etc.).
In the following section, I am going to explain this in more detail to give beginners a clear view about this fact.
I wrote the following code, and as you can see, I have defined a String variable and a StringBuilder variable. I then append a string to both of these variables:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringTest
{
   class Program
   {
       static void Main(string[] args)
       {
           string s = "Pranay";
           s += " rana";
           s += " rana1";
           s += " rana122";
           StringBuilder sb = new StringBuilder();
           sb.Append("pranay");
           sb.Append(" rana");
       }
   }
}
After the execution of the above code, we get:
s= "pranay rana rana1 rana12"
sb = "pranay rana"
To get in to the details of what happened when I appended the string, I used the RedGate .NET Reflector. The image below shows the IL of the code that I executed above. As you can see:

The String calls the Concat(str0,str1) function to append the string.
The StringBuilder calls the Append(str) function to append the string.

Read more: Codeproject