Question

Imagine the Func Func<Arguments, bool?>, where Arguments is an abstract class. Somewhere, for some reason I create a list of these functions with all kind of derived classes as arguments. Of course the type of Arguments is important for validation before the Func is called. Is there a way to get the type of Arguments?

e.g.:

public bool? test(Arguments arg) {
    Func test    = Func<SomeArguments, bool?>;
    Type argType = GetFirstArgumentType(test); // gives SomeArguments.GetType();

    if (arg.GetType() == argType) {
        return test(new SomeArguments());
    }
    return null;
}
Was it helpful?

Solution

You can use Type.GetGenericArguments to get the System.Type of the first generic argument to your Func<T,bool?>.

That being said, it would likely be easier to store a Dictionary<Type, Delegate> to hold your types, and just do a direct lookup instead.

OTHER TIPS

Based on your description, " Somewhere, for some reason I create a list of these functions with all kind of derived classes as arguments. " I might suggest that you use a parameter constraint:

 public bool? test<T>(T arg)  where T :Arguments, new()
 { 
     var type = typeof(T);

     // ...              
 }

This will get you the type checking you describe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top