1

Is there a way to compare nullable and non-nullable generics in C#?

For example:

public void function<T>()
{
    Type t = sqlreader.GetValue(pos).GetType();
}

where t is of type Int32 and T is of type Nullable<Int32>.

How can we compare t and T such that it returns true?

Florian Greinacher
  • 14,478
  • 1
  • 35
  • 53
DreX
  • 333
  • 1
  • 5
  • 17

2 Answers2

8

It's fairly unclear what you're trying to do, but you may be able to just use Nullable.getUnderlyingType:

if (t == Nullable.GetUnderlyingType(typeof(T)))
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
6

Call Nullable.GetUnderlyingType(t).
If t is a Nullable<X>, this will return typeof(X); otherwise, it will return null.

Therefore, you can write

t = Nullable.GetUnderlyingType(t) ?? t;
Type bigT = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);

if (t == bigT) 
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964