DaveDev
DaveDev

Reputation: 42225

How can I call a generic method from a reflected context?

I have a Constraints object which will get a set of rules that other objects have to adhere to.

constraints has a method called GetEnumValueRange<T>() where T is a type of Enum.

So for example, I could have an enum defined as:

[Flags]
public enum BoxWithAHook
{
    None = 0,
    Thing1 = 1,
    Thing2 = 2,
    ...
    // lots of other things that might be in the box
    ThingN = N
}

I could then get a range of values which are valid within a given context for BoxWithAHook:

var val = constraints.GetEnumValueRange<BoxWithAHook>();    

The problem is that I'm trying to use reflection to do this work. I can't specify that the type is BoxWithAHook because it could be anything that extends Enum. This is an example of what I have:

if (propertyInfo.PropertyType.BaseType == typeof(Enum))
{
    var val = constraints.GetEnumValueRange<>(); // what is the generic type here?

    // now I can use val to get the constraint values
}

Is it possible for me to specify the generic type? ideally, this would work:

constraints.GetEnumValueRange<propertyInfo.PropertyType>(); 

but it obviously doesn't

Upvotes: 1

Views: 227

Answers (2)

Lukazoid
Lukazoid

Reputation: 19426

Why not make an overload of GetEnumValueRange which takes a Type parameter, so you end up with something like this:

public class Constraints
{
    public IEnumerable GetEnumValueRange(Type enumType)
    {
        // Logic here
    }

    public IEnumerable<T> GetEnumValueRange<T>()
    {
        return GetEnumValueRange(typeof(T)).Cast<T>();
    }
}

Then you can simply use constraints.GetEnumValueRange(propertyInfo.PropertyType), I'd personally avoid reflection if there was a usable alternative like this.

Upvotes: 1

Andrei
Andrei

Reputation: 56726

You might need a little bit of reflection via MethodInfo here:

if (propertyInfo.PropertyType.BaseType == typeof(Enum))
{
    MethodInfo method = typeof(Constraints).GetMethod("GetEnumValueRange");
    MethodInfo genericMethod = method.MakeGenericMethod(propertyInfo.PropertyType);
    var val = genericMethod.Invoke(constraints, null);

    // ...
}

Upvotes: 2

Related Questions