1

I need to call a template function, something like:

void myFunc<T>();

I have the template type as string and I want to call the function using the type I have as string. For example if i want to call it for the Exception type, instead of calling:

myFunc<Exception>()

i need to do it like:

string type = "Exception";
myFunc<type>();

(i need to parse an object from json string, and i'm getting the type of the object as a string)

Is there a way to do something like this.

Thanks

0

1 Answer 1

1

The generic type has to be known at compile type in order to call a generic method the classical way.

So without reflection, you need to implicitly specify the type myFunc<string>().

However, using reflection you can specify the type at run-time. Consider the below sample:

class Program
{
    static void Main(string[] args)
    {
        string xyz = "abc";

        BindingFlags methodflags = BindingFlags.Static | BindingFlags.Public;

        MethodInfo mi = typeof(Program).GetMethod("MyFunc", methodflags);

        mi.MakeGenericMethod(xyz.GetType()).Invoke(null, null);
    }

    public static void MyFunc<T>()
    {
        Console.WriteLine(typeof(T).FullName);
    }
}

MyFunc prints System.String

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, but i think you didn't understand my question. I edit it to be more clear.
@amichai Well, you can do that using reflection only. Check my edited answer.
Thanks, I believe you meant to write Type.GetType(xyz)) instead of xyz.GetType(),
@amichai both return the same result.
the xyz.GetType() will return type string, and Type.GetType(xyz)) will return type abc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.