Sunday, April 5, 2015

ASP.Net C# Extension Methods to check if a string is blank or has a value

Here are 2 more extension methods that are simple enough, but I use on a daily basis to keep code clean and simple. I prefer to use these methods over string.IsNullOrEmpty or string.IsNullOrWhiteSpace or checking the Length of the string to keep things concise.

Code:
 public static bool IsBlank(this string Value)  
 {  
       bool ReturnValue = true;  
   
       if (Value != null)  
       {  
         ReturnValue = Value.Trim().Length == 0;  
       }  
   
       return ReturnValue;  
 }  
 public static bool HasValue(this string Value)  
 {  
      return !Value.IsBlank();  
 }  

Example usage:
 if (Key.IsBlank())  
 {  
      // code  
 }  
 if (Key.HasValue())  
 {  
      // code  
 }  

Sure you may not need both of them, or either for that matter, but when it comes to writing more readable code I like the option of having them both in my library.

0 comments: