Home > OS >  c# .NET 6.0 Determine the generic type used for a Func<T> when all you have is the base object
c# .NET 6.0 Determine the generic type used for a Func<T> when all you have is the base object

Time:02-24

Let's say we have a Method that takes a regular object as a parameter. I need to test if the object is a Func, invoke it and retrieve the return value but the generic type could be anything and I can't have a huge long list of possibilities:

    public static object? Process(object o, out Type? type)
    {
        type = null;
        if (o is Action action) action();
        else if (o is int i) { type = typeof(long); return (long)i * (long)i; }
        else if (o is double d) { type = typeof(float); return (float)(d - (long)d); }
        else if (o is Func<int> funcint) { type = typeof(int); return funcint(); }
        else if (o is Func<string> funcstr) { type = typeof(string); return funcstr(); }
        else if (o is Func<object> funcobj) { type = typeof(object); return funcobj(); }
        // ...
        // ...
        return null;
    }

CodePudding user response:

You could get the parameter type via reflection and then cast the Func to a `Delegate

Type t = o.GetType();
if (t.GetGenericTypeDefinition() == typeof(Func<>)
 && t.GetGenericArguments().Length == 1)
{
    type = t.GetGenericArguments()[0]; 
    return ((Delegate)o).DynamicInvoke(); 
}
  • Related