views:

277

answers:

1

Hi,

I am trying to use the MethodInfo MakeGenericMethod as follows:

        foreach (var type in types)
        {
            object output = null;
            var method = typeof (ContentTypeResolver).GetMethod("TryConstruct");
            var genmethod = method.MakeGenericMethod(type);
            var arr = new object[] { from, output };
            if ((bool)genmethod.Invoke(null, arr))
                return (IThingy)arr[1];
        }

Against the following generic method:

    public static bool TryConstruct<T>(string from, out IThingy result) where T : IThingy, new()
    {
        var thing = new T();
        return thingTryConstructFrom(from, out result);
    }

The problem I having is that I get an arguement exception on the MakeGenericMethod line as the type I am passing is not 'new()'

Is there a way round this?? Thanks

+2  A: 

No. You can only make closed constructed TryConstruct methods with type parameters that meet the IThingy and new constraints. Otherwise you'd be defeating the TryConstruct contract: what would happen when you called TryConstruct and it hit the new T() line? There wouldn't be a T() constructor, so you'd have violated type safety.

You need to check that type has a public default constructor before passing it to MakeGenericMethod. If you need to instantiate types with a nondefault constructor, you need to create a new method or a TryConstruct overload, perhaps one which uses Activator.CreateInstance instead of new T().

itowlson
Great answer, thanks!
Dve