Tuesday, December 29, 2015

Parsing values in C# - A Global Method for Nullable Values

Casting is important and it does cost a lot in our applications. It becomes a bit more hard when we need to treat nullable variables. Many conditions to check whether the type is nullable and has value ..etc is sometimes a too much work. What if we use a common global method that we pass the type and the value that we need to cast. Look at the below method,

 public static T Parse<T>(object value)  
     {  
       try { return (T)System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value.ToString()); }  
       catch { return default(T); }  
     }  

In above static method named as Parse,

The <T> which is the type that we need to convert the value into and the value which is the object is passed and simple enough to handle even nullable values.

 int? id = Parse<int?>(txtid.Text.Trim());  

As above, you can use this global method to do casting without any issue with nullable values.

Sometimes laziness help solving problems easier .. lol


No comments:

Post a Comment