How to determine the type of a null value

void Main()
{

   test((int?)null);

   test((bool?)null);

   test((DateTime?)null);

}

void test(object p)

{

   //**How to get the type of parameter p**
}
+3
source share
6 answers

Perhaps this may help:

void Main()
{

   test<int>(null);

   test<bool>(null);

   test<DateTime>(null);

}

void test<T>(Nullable<T> p)
where T : struct, new()
{
   var typeOfT = typeof(T);

}
+8
source

You cannot get a type because you did not pass any value. There is no difference between the three calls.

Casting a value nullis only useful to force the compiler to select a specific function overload. Since you do not have an overloaded function, the same function is called in all three cases. Without actually passing the value, your whole function will see the value null, it cannot determine the type that the caller called, which nullhas a value.

+5
source

.NET GetType():

var type = p.GetType();

, , , - . , .

, null . :

((int?)null) is int?

false. , generics, , :

void Test<T>(T p)
{
    Type type = typeof(T);
    ...
}

, , , , , , , , , .

+1

? :

  if(p != null)
  {
      p.GetType().FullName.ToString();
  }

:

p.GetType();
0

If p IsNot nothing then
    GetType(p).GetGenericArguments()(0)
End If

( , , )

0

GetType :

void test(object p) {
    if (p is int?) {
        // p is an int?
        int? i = p as int?;
    }
    else if (p is bool?) {
        // p is an bool?
        bool? b = p as bool?;
    }
}

p null, int? bool?, object Nullable.

One optimization is to use it directly as a keyword , for example:

void test(object p) {
    if (p == null)
        return; // Could be anything

    int? i = p as int?;
    if (i != null) {
        // p is an int?
        return;
    }

    bool? b = p as bool?;
    if (b != null) {
        // p is an bool?
        return;
    }
}
0
source

All Articles