27

I have the following VB.NET function, for example:

Public Function MyFunction (Of TData) (ByVal InParam As Integer) As TData

End Sub

How do I, in a function, determine if TData is a NULLable Type?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Chad
  • 23,658
  • 51
  • 191
  • 321

3 Answers3

45

One way is:

If Nullable.GetUnderlyingType(GetType(TData)) <> Nothing

... at least, the C# is:

if (Nullable.GetUnderlyingType(typeof(TData)) != null)

That's assuming you're asking whether it's a nullable value type. If you're asking whether it's a nullable value type or a class then the C# version would be:

if (default(TData) == null)

but I'm not sure whether a simple VB translation would work there, as "Nothing" is slightly different in VB.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 3
    The `<>` in your code should be `IsNot`. As you suspected, he `default` trick doesn’t work in VB since `Default(T)` doesn’t exist and is replaced by just `Nothing`, which is *always* the default value (for value types, it takes on the type’s default value). – Konrad Rudolph Mar 03 '11 at 13:54
  • It worked. ty. I'll accept after the appropriate min time elapses. – Chad Mar 03 '11 at 13:56
  • I'm sure this does work. But does typeof(T) perform boxing? If so, the results are unreliable. I'm not sure if it does or not, but I'd like to know, and haven't found the answer online easily. – Suamere Sep 11 '14 at 15:14
  • @Suamere: I don't know what you mean - `typeof(T)` always resolves to a `Type`, not a value of that type... what would be boxed? – Jon Skeet Sep 11 '14 at 15:43
  • @JonSkeet I was thinking in terms of variables, which T is obviously not. But if T were, it would be boxed as an object and lose information. Obviously that isn't the case since typeof is an expression and not a function, and T is a type parameter and not a variable. Nevermind :) – Suamere Sep 11 '14 at 18:25
7

VB.net:

Dim hasNullableParameter As Boolean = _
        obj.GetType.IsGenericType _
        AndAlso _
        obj.GetType.GetGenericTypeDefinition = GetType(Nullable(Of ))

C#:

bool hasNullableParameter = 
        obj.GetType().IsGenericType && 
        obj.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
2

You could use the code given in this answer, add an extension

public static bool IsNullable(this Type type) {
    Contract.Requires(type != null);
    return type.IsDerivedFromOpenGenericType(typeof(Nullable<>));
}

and say

bool nullable = typeof(TData).IsNullable();
Community
  • 1
  • 1
jason
  • 236,483
  • 35
  • 423
  • 525
  • This is the proper approach. Using Nullable.GetUnderlyingType is for when you KNOW its Nullable, IsDerivedFromOpenGenericType(typeof(Nullable<>)) is for ascertaining the lineage of a type. – Nick Daniels Feb 28 '14 at 15:48
  • Follow the link in the answer above to see IsDerivedFromOpenGenericType. – Nick Daniels Feb 28 '14 at 15:53