Best practices in C#


Here I have mentioned the best practices you can follow in C# and reason for the same..

  •  Performance point of view, for is much better than foreach. 
            The code we write in C# will be converted into MSIL(Microsoft Intermediate Language) code which defines the performance of  the code. We can see the MSIL code using IL Disassembler which will be installed with Visual Studio.





Here is MSIL code for above for loop. This MSIL code is only for For loop in the above mentioned program. It has code of storing the array elements into memory and displaying to the console.




Now change it to Foreach loop.




You can see the MSIL code like this. Foreach MSIL code contains
  1.  A Try catch block.
  2. Enumerator.GetCurrent
  3. Enumerator.MoveNext as the loop parameter
  4. System.Dispose is called for Enumerator in the Finally.

In short the above code looks like this.


 Note : But for arrays even if you use foreach compiler optimizes into for loop (Dotnet framework 4.0).

  • Use compare function for comparing non case sensitive instead of using ToLower(). 
         str1.ToLower() == str2.ToLower().
         Instead of this use
         string.Compare(str1, str2, true) == 0 
  • Use List instead of ArrayList if all elements are of same type. 
  •  Use string.Empty instead of “”.

  • Do provide a value of zero on simple enums. 
Consider calling the value something like “None.” If such value is not appropriate for this particular enum, the most common default value for the enum should be assigned the underlying value of zero.
             Consider an example
             Public enum ApplicationType
            {
              LCO = 1,
                          CEE = 2
             }
             Public ApplicationType application;
             Console.Write(application);
             It will return 0. So to print valid proper output we can assign default value in enum.
             Public enum ApplicationType
            {
                          None =0,
                          LCO = 1,
                         CEE = 2
            }  
  • Use StringBuilder in case of concatenation operations for the large strings or in case of loops. Reference link 6 gives more information.
  • Use IDisposable interface where it is required. After using block, it will call Dispose to automatically free resources. If you are using unmanaged resources make sure free resources by calling Dispose. Dispose is much better than finalizer. Dispose takes 1 GC cycles to free resource where as Finalizer takes 2 to N cycles depending on the elements in the finalizer queue.
  • We should throw Win32Exception on the failure of P/Invoked functions that set the Win32 last error. If the function uses some unmanaged resources, free the resource in the finally block.
  • Avoid unnecessary usage of try block. Where it can be handled logically we can use condition check to track the error.
  • It is always better not to use any hard coded values inside the methods. Instead we use const or readonly fields for the same. 
 Will be adding some more. Coding guidelines and tools will be covered in another post.

Note : Some of the things mentioned here are performance point of view. Still people use foreach because it is readable.


Reference :
  1. http://www.codeproject.com/Articles/148691/Internals-of-loops-While-For-and-ForEach
  2. http://www.dotnetperls.com/for-foreach (Only for arrays)
  3. http://www.codeproject.com/Articles/118853/Some-Best-Practices-for-C-Application-Development
  4. All in one Code Framework Coding Standards by Dan Ruder and Jialiang Ge
  5. http://www.dotnetperls.com/stringbuilder-performance
  6. http://support.microsoft.com/kb/306822 
  7. http://www.codeproject.com/Articles/111048/Some-Best-Practices-for-C-Application-Development 
  8. http://www.c-sharpcorner.com/UploadFile/dacca2/5-tips-to-improve-performance-of-C-Sharp-code/
  9. http://codebetter.com/patricksmacchia/2009/04/19/micro-optimization-tips-to-increase-performance/
  10. http://www.vcskicks.com/optimize_csharp_code.php
 


No comments:

Post a Comment

Pages