Monday, June 27, 2011

Generic Type Convert Function

It's simple method can be use as extension method for conversion types :
public static TK ConvertTo<TK>(this object value,bool isThrowException = false, 
TK defaultValue = default(TK))
{
try
{
return (TK)Convert.ChangeType(value, typeof(TK));
}
catch (InvalidCastException ex)
{
if (isThrowException)
{
throw ex;
}
return defaultValue;
}



Using example:

string value = "15";
//Method will convert string to int.
//In case val is not numeric will throw exception.
int result = value.ConvertTo();
//In case val is not numeric will return type default value.
int result1 = value.ConvertTo(false);
//In case val is not numeric will return your defined value (5).
int result2 = value.ConvertTo(false,5);

Enjoy!

kick it on DotNetKicks.com

No comments: