2

In the depths of our application there is an attempt to perform a conversion from a string to a nullable int with a Convert.ChangeType(value, castType). In this case the values are as follows:

value: "00010"
castType: Nullable<System.Int16>

The issue is that I am receiving the following error

Invalid cast from 'System.String' to 'System.Nullable`1[[System.Int16}

I had (obviously incorrectly) believed this was similar to a cast or Convert.ToInt16() but I've verified it's not the same by testing the following two lines of code.

Int16 t = Convert.ToInt16("00010");
object w = Convert.ChangeType("00010", typeof(short?));

As you might suspect, the first succeeds whereas the second fails with the error message above.

Is it possible to use ChangeType in this fashion by making an adjustment or should I look at a refactor?

McArthey
  • 1,614
  • 30
  • 62
  • 1
    I ended up doing this based upon the information at the link: `Convert.ChangeType(value, Nullable.GetUnderlyingType(castType) ?? castType);` – McArthey Nov 13 '16 at 04:08

2 Answers2

3

According to Convert.ChangeType:

The ChangeType(Object, Type) method can convert a nullable type to another type. However, it cannot convert another type to a value of a nullable type, even if conversionType is the underlying type of the Nullable<T>. To perform the conversion, you can use a casting operator (in C#) or a conversion function (in Visual Basic).

So, try:

var w = (short?)Convert.ChangeType("00010", typeof(short));
AlexD
  • 32,156
  • 3
  • 71
  • 65
2

You'll need to write something like this:

var value = "00010";
short? w = value == null ? null : (short?)Convert.ChangeType("00010", typeof(short));

ChangeType will not work with Nullable<T> - and if we have a value for value, we assume we have a value for the converted type

Rob
  • 26,989
  • 16
  • 82
  • 98
  • This is valuable but my values for the types are set at runtime with `typeof(T).GetProperty().PropertyType` so I'm not certain if I can do an explicit cast – McArthey Nov 13 '16 at 01:59