Nullable<T> types: Reflection doesn't determine a Nullable type, overloadng is cool solution, but using inferred types is better!

 

To get the type of a variable, we can usually use instance.GetType();  But for Nullable<T> types, GetType reflection returns the returns the underlying type.

That is:

 

            int i = 0;

            isInteger = i.GetType().Equals(typeof(int)); //isInteger == true

 

but reflection on a Nullable<T> varaible returns the underlying type

            Nullable<int> iNullable = 0;

            isNullable = iNullable.GetType().Equals(typeof(Nullable<>)); //isNullable == false; GetType returns int32

 

 

 

 

Overloading is cool way to test for Nullable<T> variable instance, but inferred typing is even better!

        //Using overloading, you can determine if a varaible is a nullable type, but you must know all possible test types:

        ///<summary>Identify a Nullable Type</summary>

        public static bool IsNullableType(Nullable<int> n)

        {

            return true;

        }

        public static bool IsNullableType(int i)

        {

            return false;

        }

 

        //Using an inferred TypeParam, you can determine if a varaible is a nullable type for any variable type!:

        ///<summary>Identify a Nullable Type</summary>

        public static bool NullableType<T>(T value)

        {    var type = typeof(T);    return (type.IsGenericType && type.GetGenericTypeDefinition() == typeof (Nullable<>));

        }

 

        static void Main()

        {

            bool isNullable;

 

            int i = 0;

            bool isInteger = i.GetType().Equals(typeof(int)); //isInteger == false;

            isNullable = IsNullableType(i); //isNullable == false;

            isNullable = NullableType(i); //isNullable == false;

 

            Nullable<int> iNullable = 0;

            isNullable = iNullable.GetType().Equals(typeof(Nullable<>)); //isNullable == false;

            isNullable = IsNullableType(iNullable); //isNullable == true;

            isNullable = NullableType(iNullable); //isNullable == true;

 

            Nullable<double> d = 0;

            isNullable = d.GetType().Equals(typeof(Nullable<>)); //isNullable == false;

            isNullable = IsNullableType(d); //Compiler Error      1     The best overloaded method match for xxx.Program.IsNullableType(int?)' has some invalid arguments

            isNullable = NullableType(d); //isNullable == true;

         }

 

 

 

 

 

 

 


Posted Mar 05 2009, 11:45 AM by Gary
Copyright Summit Software Company, 2008. All rights reserved.