C# Programming Performance Tips - Part Two - String Equals

You can read all the C# performance tips from the following links,

In the below code, we would like to check if the str variable's value is equal to the string “Akshay” or not. And, let us assume that somehow, we are getting the str variable value as null.

  1. try {  
  2.     string str = null;  
  3.     if (str.Equals("Akshay")) {  
  4.         Console.WriteLine("if");  
  5.     } else {  
  6.         Console.WriteLine("else");  
  7.     }  
  8. catch (Exception ex) {  
  9.     Console.WriteLine(ex.Message);  
  10. }  
  11. Console.ReadLine(); 

In this case, str.Equals will throw a null reference exception.

Now, let’s think in a little bit of a different way. Rather than using Equals method with str, let’s use it with our value, i.e., “Akshay”.

  1. try {  
  2.     string str = null;  
  3.     if ("Akshay".Equals(str)) {  
  4.         Console.WriteLine("if");  
  5.     } else {  
  6.         Console.WriteLine("else");  
  7.     }  
  8. catch (Exception ex) {  
  9.     Console.WriteLine(ex.Message);  
  10. }  
  11. Console.ReadLine();  

In this case, the code will execute the else part instead of throwing a null reference exception.