Is there anyway to know this?
I found one post that asked a very similar question at How to check if an object is nullable? The answer explains how to determine if an object is nullable if there is access to a Generic Type Parameter. This is accomplished by using Nullabe.GetUnderlyingType(typeof(T))
. However, if you only have an object and it is not null, can you determine if it is actually a Nullable ValueType?
In other words, is there a better way than checking every possible nullable value type individually to determine if a 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
I found this article at MSDN, and it says you can't determine if a type is a Nullable struct via a call to GetType()
.
-
Update #2
Apparently the method I suggested doesn't work either because int x = 4; Console.WriteLine(x is int?);
is True. (See the comment)