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...