Search code examples
c#.netgenericsgeneric-programming

Alternative to SomeFunction<SomeType.GetType()>(SomeArgument)


I have a generic function as follows:

public static T Function<T>(Argument arg)
{
    //DO FUNCTION STUFF
}

I want to call this function using a Type I get from FieldInfo.FieldType like so:

Function<someFieldInfo.FieldType>(arg);

However, this is not allowed. And neither is:

Function<typeof(SomeType)>(arg);

I am far from a C# expert so excuse if this is a stupid question. But why doesn't this work? And how can I work around it to get similar functionality?


Solution

  • Since you can't accept a comment as an answer I just thought I would write it hear.

    First Question: Why can't you pass the Type you get from fieldInfoInstance.FieldType to a generic function

    If I have understood everything correctly, it is as @Lee pointed out, what is returned from fieldInfoInstance.fieldType is an instance of a class that extends type where as a generic function expects a Type Paramater.

    Second Question: How can you work around not being able to do so?

    I ended up doing like @silkfire and @Lee suggested, having a function that takes the type as an argument instead of an generic function. However I still prefer generic functions over casting when using a function so I ended up using two functions.

    private static object Function(Type type, Arguments args)
    {
        // DO FUNCTION STUFF
    }
    

    and

    public static T Function<T>(Arguments args)
    {
        return (T) Function(typeof(T), args);
    }
    

    This way the user can still call the function in a generic way, and by doing so doesn't have to cast the returned object (In my opinion alot cleaner) and I can call the function and pass in a Type. The non-generic function doesn't have to be public because the only time I need to pass the Type using a Type Instance instead of a Type Parameter is when recursively calling the function from within.