Reputation: 9477
Im trying to create an extension method in an enviroment where lots of reflection is used.
The methods purpose is to recreate what default() does at runtime.
It works fine for everything but those Nullable<> types. Even ?-Types working correctly.
I have no Idea how i can find out, if the value assigned to an object variable is a Nullable<> and not a "regular valute type"
The Nullable.GetUnderlyingType-Method returns null in that case, but works on ?-Types.
We know that default(Nullable) == null. My extension method yields wrong results when the Nullable gets 0 assigned, since 0 == default(int).
I hope you get what Iam trying to explain here, in short: - How do I determine if a "random" object is a Nullable and not an int ?
The Method looks something like this (removed any caching for simplicity) I took parts from here How to check if an object is nullable?
public static bool IsDefault(this object obj)
{
if(obj == null)
return true;
else
{
Type objType = obj.GetType(); // This gives int32 for Nullabe<int> !?!
if(Nullable.GetUnderlyingType(objType) != null)
return false;
else if(objType.IsValueType)
return Object.Equals(obj, Activator.CreateInstance(objType);
else
return false;
}
}
To make it more clear I cannot use generic stuff...
Upvotes: 1
Views: 215
Reputation: 5514
Seems you can find out whether a type is nullable by doing something like this:
public static bool IsDefault<T>( this T obj )
{
var t = typeof( T );
var isNullable = t.IsGenericType && t.GetGenericTypeDefinition() == typeof( Nullable<> );
// ...
}
Your method must be generic for this to work, though.
Upvotes: 0
Reputation: 13106
From http://msdn.microsoft.com/en-us/library/ms366789.aspx:
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {…}
Upvotes: -1
Reputation: 56556
When a nullable type is boxed to an object
, the fact that it was nullable is lost: it either becomes a plain-old int
, or a plain-old null
. If your object is already stored as type object
, you cannot recover this.
Upvotes: 3
Reputation: 164341
You can't do this, because when you call the method, the nullable struct is boxed to be object
, and becomes either null
or an Int32
value. This is explained in an earlier answer: Why GetType returns System.Int32 instead of Nullable<Int32>?
If your variable is typed as an object in the place where this method is called, I don't think you can get the information you need - it is already boxed.
Upvotes: 3