1

I was to dynamically return the default value of a type, but I can't pass the default keyword a variable of type Type.

Why not?

Eg:

    private object GetSpecialDefaultValue(Type theType)
    {
        if (theType == typeof (string))
        {
            return String.Empty;
        }
        if (theType == typeof (int))
        {
            return 1;
        }
        return default(theType);
    }

Gives me the compile time error:

The type or namespace name 'theType' could not be found (are you missing a using directive or an assembly reference?)

Ev.
  • 7,109
  • 14
  • 53
  • 87
  • possible duplicate of [Programmatic equivalent of default(Type)](http://stackoverflow.com/questions/325426/programmatic-equivalent-of-defaulttype) – Mitch Feb 24 '14 at 06:03
  • Because default is resolved at compile time. Since the type you're giving it is not known at compile, it doesn't work. – Yev Feb 24 '14 at 06:06

2 Answers2

5

You can only use default with generic type parameter.

The default keyword can be used in the switch statement or in generic code:

from default (C# Reference)

How about that one?

private object GetSpecialDefaultValue<T>()
{
    var theType = typeof(T);

    if (theType == typeof (string))
    {
        return String.Empty;
    }
    if (theType == typeof (int))
    {
        return 1;
    }
    return default(T);
}

Update

You can try following instead of default, but I'm not 100% sure it will work.

return theType.IsValueType ? (object)(Activator.CreateInstance(theType)) : null;
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • 1
    +1. Note that `default(SomeType)` can be used anywhere, but makes not much sense in non-generic code where `null`/`new SomeValueType` can give more clarity. – Alexei Levenkov Feb 24 '14 at 06:44
  • I would definitely make note of Alexi's comment in your post if only for the sake of accuracy. – Hardrada Feb 24 '14 at 06:59
2

The reason that default does not take an instance of Type is that there is no default instruction in IL. The syntax of default translates to ldnull or initobj T depending upon whether the type is a value type or not.

If you want to get a default value from a Type, perform the same logic as given in this other question:

public static object GetDefaultValue(Type t)
{
    if (!t.IsValueType || Nullable.GetUnderlyingType(t) != null)
        return null;

    return Activator.CreateInstance(t);
}
Community
  • 1
  • 1
Mitch
  • 21,223
  • 6
  • 63
  • 86