1

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?

Sebi
  • 3,879
  • 2
  • 35
  • 62

1 Answers1

1

Because int? is shorthand for Nullable<int> which is different to int. Those are two different types in .Net. If you want to cast int? to int or vice versa you have to do it manually.

Edit

Conversion from double to int is defined whereas conversion from nullable types to normal numerical types is not.

Sjoerd222888
  • 3,228
  • 3
  • 31
  • 64
  • 1
    The problem is not that they are two different types. If you did it with `double` it would work despite `double` and `int` being different types. The problem is that the conversion of `int` to `Nullable` is not defined. You are right that in this case code needs to be written to do the conversion though. – Chris Nov 04 '15 at 11:18