Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Reflection, using MakeGenericMethod with method that has the 'new()' type constraint

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

like image 353
David Avatar asked Jan 30 '26 17:01

David


1 Answers

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

like image 112
itowlson Avatar answered Feb 01 '26 05:02

itowlson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!