0

Possible Duplicate:
.NET : How do you get the Type of a null object?

Basically I would like code like one of the following to work without a null reference error:

int? i1 = default(int?);
int? i2 = new Nullable<Int32>();
int? i3 = new int?();
var t1 = i1.GetType();
var t2 = i2.GetType();
var t3 = i3.GetType();

I would hope/expect that I would be able to obtain the type from the i objects above without a null reference exception.

If this is not possible, how would I be able to create a reference to a Nullable Int while maintaining a null value.

UPDATE: for those interested and don't want to sift through the not totally applicable answers in the linked question, the solution is:

private void Example()
{
    var i = default(int?);
    var t = this.GetDeclaredType(i);
}

private Type GetDeclaredType<T>(T obj)
{
    return typeof(T);
}
Community
  • 1
  • 1
Chris Nelson
  • 105
  • 6

0 Answers0