How to determine if a non-zero object is a Nullable structure?

Does anyone even know this?

I found one post that asked a very similar question in How to check if an object is null? The answer explains how to determine if an object is null if there is access to a parameter of a general type . This is achieved using Nullabe.GetUnderlyingType(typeof(T)). However, if you only have an object and it is not NULL, you can determine if this is a Nullable ValueType?

In other words, is there a better way than checking every possible type of a valid NULL value to determine if boxed struct is a value type?

void Main(){
    Console.WriteLine(Code.IsNullableStruct(Code.BoxedNullable));
} 


public static class Code{
    private static readonly int? _nullableInteger = 43;

    public static bool IsNullableStruct(object obj){
                  if(obj == null) throw new ArgumentNullException("obj");
                  if(!obj.GetType().IsValueType) return false;
                  return IsNullablePrimitive(obj);
            }
    public static bool IsNullablePrimitive(object obj){
         return obj is byte? || obj is sbyte? || obj is short? || obj is ushort? || obj is int? || obj is uint? || obj is long? || obj is ulong? || obj is float? || obj is double? || obj is char? || obj is decimal? || obj is bool? || obj is DateTime? || obj is TimeSpan?;
    }

    public static object BoxedNullable{
        get{ return _nullableInteger; }
    }
}

-

Update

MSDN , , Nullable struct GetType().

-

# 2

-, , , , int x = 4; Console.WriteLine(x is int?); - True. (. )

+5
4

Jon Skeet :

, - Nullable int

BoxedNullable IsNullableStruct, object , 43, . x is int? true int, , .

, , , .

+4

, . Nullable <INT> int. , Nullable.

, IsNullablePrimitive true, -Nullable int!

+1

Nullable < > - . Nullable < > , / "null" , . GetType() , Nullable < > . . Nullable < > .

0

, :

protected bool IsNullableType(Type type)
{
    if(!type.IsGeneric)
        return false;

    return type.GetGenericDefinition() == typeof(Nullable<>);
}

:

var type = typeof(Nullable<>);
var type2 = new Nullable<int>().GetType().GetGenericDefinition();
-1

All Articles