.NET 4.0: How can I get the base type of a generic parameter if it is Nullable?

Note. I am not trying to determine if the general parameter is null. I want to know if it can be null, what is the null base 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

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

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

It looks like I need to get the base type in order to create an nullable instance of this type using reflection. Not sure how to get around this catch-22.

Can someone point me to a way that I can determine if the generic type is null, and if so, how can I get its base type?

+3
source share
1 answer

# :

Type underlyingType = Nullable.GetUnderlyingType(typeof(T));
if(underlyingType != null) {
    .. is nullable, with underlying-type as described
}
+3

All Articles