Iam confused by the ChangeType Method of .Net. I wrote a extension method to convert object values (which come from database in my cases) in the expected type. So long iam not using nullable types this works pretty good.
Iam doing this so far:
public static T ConvertTo<T>(this object value)
{
T returnValue = default(T);
if ((value != null) &&
(value != DBNull.Value))
{
returnValue = (T)Convert.ChangeType(value, typeof(T));
}
return returnValue;
}
If i call:
int test = myObject.ConvertTo<int>();
Iam getting the int value or 0 if myObject doesn't contain a int. Because it is possible to do the following:
int? test = 5;
I thought there is no problem to cast a int to int?. But if i call this:
int? test = myObject.ConvertTo<int?>();
Iam getting System.InvalidCastException. Invalid cast from System.Int32 to System.Nullable`1
The Exception is thrown in the Convert.ChangeType line.
Somebody knows why?