non-generic "default"

Generic types are kind of nice, but...

the typical use of the default keyword in the generic context provides an initialization of a variable with a default value and it takes the generic type token as a parameter - nice function: x = default(T);

now I face a situation where I know the type and need the default value/instance of the type:
object DefaultValue(Type t)
{
return default(t); // doesn't work of course
}
Is there a substitute for "default" for the non generic use that I miss here The situation seems to be easier, because the type is actually known, but if I am not wrong no such function exists. The only way to achieve the same functionality is, e.g. going through the Activator and checking for primitive or complex types.

Would be nice to have, don't you think



Answer this question

non-generic "default"

  • Chas75287

    David M. Kean - MSFT wrote:

    I haven't tested this, but how about this:



    public static object DefaultValue(Type t)
    {
    if (t.IsValueType)
    {
    return Activator.CreateInstance(t);
    }
    return null;
    }

    I can't say that I've ever needed to do this in 4 years of using .NET.



    I have. It's used heavily in Factory based patterns.


  • Yogesh2810

    That was more suggestion of a function to add to the C# vocabulary, maybe to the TypeDescriptor, but your function looks pretty much the same as the one I wrote.

    First time I was looking for a function like that, too. The scenario was, that I created kind of an abstract instance of a XML Schema where an element is (string name, Type type, object value). Name and type were extractable from the Schema, but a generic "default" value was missing for this scenario.

    Nevertheless, it was just a suggestion...


  • Mike Champion - MSFT

    John,

    You can make product suggestions on the Microsoft Product Feedback Center. Be sure to include any scenarios where such a feature would be useful.



  • Zilog8

    I haven't tested this, but how about this:



            public static object DefaultValue(Type t)
            {
                if (t.IsValueType)
                {
                    return Activator.CreateInstance(t);
                }
                return null;
            }

     

    I can't say that I've ever needed to do this in 4 years of using .NET.



  • non-generic "default"