1

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

Community
  • 1
  • 1
CSharpie
  • 9,195
  • 4
  • 44
  • 71

4 Answers4

3

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.

Community
  • 1
  • 1
driis
  • 161,458
  • 45
  • 265
  • 341
3

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.

Tim S.
  • 55,448
  • 7
  • 96
  • 122
  • @CSharpie I'd recommend choosing based on which answer is better - in this case, I'd agree that it's driis's - not based on a small time difference. – Tim S. Jul 03 '13 at 17:15
0

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.

Chris
  • 5,442
  • 17
  • 30
-1

From http://msdn.microsoft.com/en-us/library/ms366789.aspx:

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {…}
Mike Cheel
  • 12,626
  • 10
  • 72
  • 101