3

Note: I am not trying to determing whether or not a generic parameter is nullable. What I want to know is, if it is nullable, what is the nullable's underlying type?

Here is what I am trying:

Function CreateTdParameter(Of T)(Name As String, Value As T) As TdParameter

    Dim TdType As TdType
    Dim ValueType As Type = GetType(T)

    If ValueType.IsGenericType Then
        Dim GenType As Type = ValueType.GetGenericTypeDefinition()
        If GenType = GetType(Nullable(Of )) Then
            ValueType = Activator.CreateInstance(GenType.MakeGenericType(New Type() {ValueType}))
            ValueType = Nullable.GetUnderlyingType(ValueType.GetGenericTypeDefinition().UnderlyingSystemType)
        End If
    End If

    If ValueType = GetType(String) Then
        TdType = Teradata.Client.Provider.TdType.VarChar
    ElseIf ValueType = GetType(Integer) Then
        TdType = Teradata.Client.Provider.TdType.Integer
    ElseIf ValueType = GetType(DateTime) Then
        TdType = Teradata.Client.Provider.TdType.Timestamp
    Else
        Throw New NotImplementedException(String.Format("{0} not expected.", Value.GetType))
    End If

    Return CreateTdParameter(Name, Value, TdType, ParameterDirection.Input)

End Function

It results in the following error when a DateTime? is passed through the Value parameter:

GenericArguments[0], 'System.Nullable1[System.DateTime]', on 'System.Nullable1[T]' violates the constraint of type 'T'.

It appears that I need to get the underlying type in order to instantiate a nullable of that type using reflection. Not sure how to get around this catch-22.

Can anyone point me to a way that I can tell whether or not a generic type is nullable and, if it is, how I can get its underlying type?

jaredk
  • 986
  • 5
  • 21
  • 37
oscilatingcretin
  • 10,457
  • 39
  • 119
  • 206
  • 5
    isn't that simply `Nullable.GetUnderlyingType(typeof(T))` ? – Marc Gravell May 10 '12 at 14:54
  • 1
    @MarcGravell: It looks like a previous answer of yours (though a C# version) should fit here nicely: http://stackoverflow.com/questions/374651 – Paul Sasik May 10 '12 at 15:00
  • Marc, I can't believe it was that simple. My previous code was using Nullable.GetUnderlyingType(), but it was returning null for some reason, hence why I moved on to reflection. I was obviously doing something wrong! Please add that as answer so I can mark it. – oscilatingcretin May 10 '12 at 15:14
  • @MarcGravell: Cool, handy method. Never seen it before, but I would have probably implemented it exactly the same ;p There should be more reflection helper methods in the framework. – leppie May 10 '12 at 15:23

1 Answers1

3

I'll use C# for the example:

Type underlyingType = Nullable.GetUnderlyingType(typeof(T));
if(underlyingType != null) {
    .. is nullable, with underlying-type as described
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900