McArthey McArthey - 2 months ago 17
C# Question

Unable to ChangeType from string to int?

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?

Rob Rob

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