Click here to Skip to main content
15,881,092 members
Articles / Programming Languages / C#
Tip/Trick

.NET Coding Best Practices

Rate me:
Please Sign up or sign in to vote.
2.58/5 (27 votes)
20 Jan 2010CPOL2 min read 49.5K   10   8
.NET Coding Best Practices - Vinayak's thumb rulesDo not hard code strings/ numerics. Instead of that use constants as shown below.Bad practice int Count; Count = 100; if( Count == 0 ) { // DO something… }Good practice int Count; Count = 100; private...
.NET Coding Best Practices - Vinayak's thumb rules


  1. Do not hard code strings/ numerics. Instead of that use constants as shown below.

    Bad practice

    C#
    int Count;
    Count = 100;
    if(  Count  ==  0 )
    {
     // DO something…
    }
    


    Good practice

    C#
    int Count;
    Count = 100;
    private static const int ZERO  =  0;
    if(  Count  ==  ZERO )
     {
       // DO something…
     }
    


  2. For string comparison - Use String. Empty instead of “”

  3. By default keep the scope of member variables to ‘private’, based on the needs expand the scope either to protected or public or internal.


    1. Other advantage of making the scope private by default is that during XMLSerilaization, by default it will serialize all the public members.


  4. When we have to manipulate the strings inside a loop, use StringBuilder instead of string as shown below.

    Bad practice

    C#
    String  temp = String.Empty;
    for( int I = 0 ; I<= 100; i++)
    {
      Temp += i.ToString();
    }
    


    Good practice

    C#
    StringBuilder sb = new StringBuilder();
    for ( int I = 0 ; I<= 100; i++)
     {
       sb.Append(i.ToString());
      }
    


  5. Prefer Arrays over Collections for simple operations.

  6. Prefer Generic Collections over ArrayList

  7. Prefer Generic Dictionaries over HashTable *.

  8. Prefer StringCollections and StringDictionaries for String manipulations and storage.

  9. Use the appropriate data types.

    For ex: if you want to check for any status, prefer bool rather than int.

    Bad practice

    C#
    int Check = 0;
    if(Check == 0)
     {
       // DO something
      }
    


    Good practice

    C#
    bool Check = false;
    if(!Check)
      {
        // DO something
      }
    


  10. Use ‘as’ operator for type casting and before using that resultant value check for null.

    C#
    class A
     {
     }
    
    class B : A
     {
     }
    
    B objB = new B();
    A objA1  = (A) objB;
    A objA 2 = objB as A;
    
    if( objA2 != null)
    {
     //Do something
    }


  11. For WCF proxy creation, use the using statement

    C#
    using(Cerate the proxy)
     {
       //Do the required operation
      }
    


  12. Follow ‘Acquire late, release early’ rule for expensive resources such as Connection, File etc.

    For ex : if you want to make use of SqlConnection Object for any data operations, create the instance at the method level rather than at the class level.

    C#
    class MyData
     {
         public MyData()
           {
           }
         public List<Customer> GetAllCustomer()
           {
           using(SqlConnection objConnection = new SqlConnection("Connection string"))
             {
               //Do the operation and get the required data..
             }
           }
    }
    


    If you want to create the SqlConnection instance at the class level, ensure that you are implementing the IDisposable for the class and doing the cleanup of SqlConnection instance at the Dispose();

    C#
    class MyData : IDisposable
     {
        SqlConnection objConnection = default(SqlCOnnection);
        public MyData(){
          objConnection = new SqlCOnnection("Connection string");
        }
        public List<Customer> GetAllCustomer(){
          // By using objConnection get the required data
        }
        public void Dispose(){
         // Do the cleanup of SqlCOnnection
         if( objConnection != null ){
            if( objConnection.State == ConnectionState.Open){
           objConnection.Close();
            }
         }
       }
    }
    


  13. If you do not want anybody to extend your class functionalities, make it ‘sealed’ to get the inlining and compile time benefits

  14. Avoid declaring the ‘destructor’ for every class. This will increase the life time of the class which un necessarily makes them long lived

  15. Prefer using Thread Pool over manual threading.

  16. Do not make any calls to a method from the loop.

    For ex :

    Bad practice

    C#
    for( int i = 0; i<= 100; i++)
    {
    	Calculate(i);
    }


    Good practice

    C#
    for( int i = 0; i<= 100; i++)
    {
      //Inline the body of Calculate.
    }


  17. Do not handle exceptions inside a loop, rather handle looping logic inside try/catch

    For ex:

    Bad practice

    C#
    for(int i = 0 ; i<= 100; i++){
       try{
       }
       catch(Exception ex){
          throw ex;
       }
    }


    Good practice

    C#
    try{
      for(int i = 0 ; i<= 100; i++){
      }
    }
    catch(Exception ex){
     throw ex;
    }
    


  18. Do not handle application logic by using Exception.

    For ex :

    Bad practice

    C#
    try{
      int  x,y,z;
      x = 0;
      y = 10;
      z = y/x;
     }
    catch(DevideByZeroException ex){
      throw ex;
    }
    


    Good practice

    C#
    private static const int ZERO  =  0;
    try{
      int x,y,z;
      x = 0;
      y = 10;
      if( x != ZERO){
        z = y/x;
      }
     }
    catch(Exception ex){
     }
    


  19. Prefer for/while loop over foreach

  20. For communication between the layers, prefer Data Transfer objects over DataSet/DataTables.

I hope this will help you all to improve the code quality!!

Happy programming

Regards,
-Vinayak

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect MindTree Ltd
India India
Motivated achiever who guides organizations in applying technology to business settings, provides added value, and creates project deliverables in a timely manner. An experienced Technical Consultant, have successfully led large project teams of more than 20 people from requirements gathering to implementation and support using C#, .NET ,ADO.NET, ADO.NET Entity Framework,ASP.NET,ASP.NET MVC, WCF and SQL Server.

Comments and Discussions

 
GeneralImprove the snippet codes Pin
Adaying23-Sep-15 2:08
Adaying23-Sep-15 2:08 
GeneralMy vote of 3 Pin
Chamila Nishantha15-Nov-12 17:39
Chamila Nishantha15-Nov-12 17:39 
GeneralSome good ideas... Pin
Sebastian Br.25-Jan-10 22:05
Sebastian Br.25-Jan-10 22:05 
General[My vote of 2] Comment on the article Pin
jstemper21-Jan-10 6:27
professionaljstemper21-Jan-10 6:27 
General#1, #2, #9, #15, #17, #18, #19 Pin
supercat920-Jan-10 6:05
supercat920-Jan-10 6:05 
#1 -- Constants

My primary rule for using named constants is to determine what would have to happen for a number to be changed. If there are multiple places in the code which must all have the same value for things to work properly, then named constants should be used. If a particular number is used in only one place, but finding that spot in the event the number must change would be difficult, a named constant (defined in an easier-to-find location) may be appropriate. If a number is only used in one place, but other places in future may use that number (and have to match), a named constant is probably appropriate. On the other hand, something like:
Constant NumberOfTimesToBeep As Integer = 3
For I=1 to NumberOfTimesToBeep
  Beep
Next

is often not really any better than
For I=1 to 3
  Beep
Next

unless the same constant is, or is likely to be, used multiple times. In the latter case, anyone who sees the number "3" will be able to see what it actually does. In the former case, one would have to look at both the code and the declaration to see what's going on.

#2 -- What advantage is there to String.Empty rather than ""? Shouldn't string literals get interned? The latter formulation is more concise and easier to read.

#9 -- While Boolean data types are often better than integers, integers can be used with Interlocked operations.

#15 -- I've read various articles indicating one should use the thread pool, but I am leery of using a global resource whose usage by other code will often be unknown and unknowable. If two threads will need to wait for each other, using the system threadpool for them would seem to be a recipe for deadlock. I could certainly understand that using some form of thread pooling is often good, but the system thread pool seems hokey.

#17 -- The question of whether to handle exceptions inside or outside a loop is one of logic rather than style. If an exception is thrown in the loop, can useful work be done by the remainder of the loop? If so, the exception must be inside. If not, it should probably be outside. The one caveat I would add is that if an exception is thrown within a loop, one may want to check at run-time to ensure that no condition exists which would cause the rest of the loop to fail.

#18 -- One should early-check conditions which would be likely to cause exceptions, but be very leery of expecting to catch all exceptional conditions. If one didn't have "Double.TryParse" available, for example, one could try to pre-validate the input before calling Double.Parse, but catching all possible invalid inputs while allowing all valid ones would be difficult. On the other hand, pre-checking the more common invalid-input scenarios may be worthwhile.

#19 -- What's wrong with foreach, in situations where one is enumerating an IEnumerable?
GeneralIf these are considered best practices... PinPopular
bhogan22-Dec-09 7:14
bhogan22-Dec-09 7:14 
GeneralMost are good tips... PinPopular
Ron Beyer22-Dec-09 3:44
professionalRon Beyer22-Dec-09 3:44 
GeneralRe: Most are good tips... Pin
kornman0012-Jan-10 5:20
kornman0012-Jan-10 5:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.