Sunday, July 17, 2011

Convert type extension

Current extension allow to convert type to type with/without throwing exception:
public static T ConvertTo(this object value,  
                 bool isThrowException = false
              T defaultValue = default(T))
       {
           try
           {
               return (T)Convert.ChangeType(value, typeof(T));
           }
           catch (Exception ex)
           {
               if (isThrowException)
               {
                   throw ex;
               }
           }
           return defaultValue;
       }

Using:
string numberString = "5";
//Return correct or default value and not throwing exception
int numInt = numberString.ConvertTo<int>();
//Return correct or default value and throwing exception
numInt = numberString.ConvertTo<int>(true);
//Return correct or value(-1) and not throwing exception
numInt = numberString.ConvertTo<int>(false,-1);

No comments:

Post a Comment