views:

27

answers:

1

I'm refactoring some code that was originally designed with generics to also work with reflection. The particular code base has default(T) scattered throughout. I've created a method that will look similar named Default(T), but I don't think my implementation is correct.

Essentially my implementation looks like this:

private object Default(Type type)
{
    return (type.IsByRef ? (object)null : 0;
}

I am getting class cast exceptions. The purpose of the reflection is to enable attributes to drive the functionality instead of the explicitly declaring objects. Basically we have one set of attributes to mark properties that will get serialized, and now we want to use those same attributes to populate a property dialog box. Because I'm working reflectively, generics are out of the picture.

+2  A: 

Why do you say generics are out of the picture?

    public static object GetDefault(Type t)
    {
        Func<object> f = GetDefault<object>;
        return f.Method.GetGenericMethodDefinition().MakeGenericMethod(t).Invoke(null, null);
    }

    private static T GetDefault<T>()
    {
        return default(T);
    }
Rob Fonseca-Ensor
Hmm... Let me try that when I get back to the office. I may not have to go through all the trouble I have so far.
Berin Loritsch
If only I knew this existed sooner. Having come from a Java background, I didn't even consider this possible (Java's Generic support is broken and has minimal reflection help).
Berin Loritsch