0

I want to convert a null value into a Nullable(Of )-Type. I can cast it with CType(), but not convert it with System.Convert.ChangeType().

Is there a way to do so? Why it throws an exception?

Dim b as Boolean? = CType(Nothing, Boolean?) 'ok
System.Convert.ChangeType(Nothing, GetType(Boolean?)) 'Throws System.InvalidCastException
user11909
  • 1,235
  • 11
  • 27
  • 2
    http://stackoverflow.com/questions/3531318/convert-changetype-fails-on-nullable-types – Eric May 29 '15 at 09:49
  • 2
    What's the problem in _simply_ using `Nothing` directly as in `Dim b As Boolean? = Nothing` ? – Sehnsucht May 29 '15 at 12:24
  • @Sehnsucht It's a code fragment. In my project it could be every type, not only `Boolean?`. – user11909 Jun 02 '15 at 05:04
  • @user2190035 I still don't see where's the problem if you want a Nullable without value simply use Nothing. It works for every type which can be Nullable because Nothing is not really equivalent to c# null ; but closer to C# default. Maybe I'm missing something... – Sehnsucht Jun 02 '15 at 13:03
  • @Sehnsucht It also could be every value, not only Nothing. – user11909 Jun 05 '15 at 04:48
  • @user2190035 and ? you could also assign an "underlying value" directly to a nullable ; see this [fiddle](https://dotnetfiddle.net/zFMR5n) for example – Sehnsucht Jun 05 '15 at 14:11

1 Answers1

2

Is there a way to do so?

Dim valueNothing = ConvertHelper.SafeChangeType(Of Boolean)(Nothing)
Dim valueTrue = ConvertHelper.SafeChangeType(Of Boolean)(True)
Dim valueFalse = ConvertHelper.SafeChangeType(Of Boolean)(False)
' ...
Class ConvertHelper
    Shared Function SafeChangeType(Of T As Structure)(ByVal value As Object) As T?
        Return If(value Is Nothing, Nothing, DirectCast(Convert.ChangeType(value, GetType(T)), T?))
    End Function
End Class

Why it throws an exception?

Due to Convert.ChangeType method implementation:

if( value == null ) {
    if(conversionType.IsValueType) {
        throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCastNullToValueType"));
    }
    return null; 
}
DmitryG
  • 17,677
  • 1
  • 30
  • 53