Three simple tricks for better C# code

Here are 3 tricks that once you start using them can save you a lot of typing when dealing with C#.


1. The Null Coalescing Operator (??) This is a short-cut for the ternary operator (?:) checking against a null:
string name = value;  
      
   if (value == null)  
   {  
     name = string.Empty;  
   }  
Can now be condensed into one line:
 string name = value ?? string.Empty;  
2. Auto properties There is no need to define a variable for simple backing fields for most properties in C#. In fact most things like int, strings, double i just let the compiler handle it.
 public class MyPoint  
   {  
    public int X { get; set; }  
    public int Y { get; set; }  
  }  
3. Is vs As You should try and avoid the is operator when you can do an as cast. The is requires two casts where the as does just one. Even with the added null check it's always going to be faster to do an as vs is.
 var sq = Square as Shape;  
   if ( sq != null )  
   {  
     volume = sq.CalculateVolume();  
     // ...  
  }  

Comments

Thank you for sharing the codes!

Popular Posts