2
public class A<T>
{
    public static void B()
    {
    }
}

How I can call method B like this:

Type C = typeof(SomeClass);
A<C>.B()
3
  • Can you add some context around the second code fragment, such as the declaration of C? Commented Oct 31, 2013 at 8:32
  • Is your intention to use: A<SomeClass>.B();? C is a variable, not a type. Commented Oct 31, 2013 at 8:55
  • @AlexFilipovici no. In future is may be a dynamic list of types and call this method for any of them. Commented Oct 31, 2013 at 8:57

1 Answer 1

6

You need to use reflection. MakeGenericType allows you to get the Type with specific generic arguments and then you can get and call any method on it as you like.

void Main()
{
    Type t = typeof(int);
    Type at = typeof(A<>).MakeGenericType(t);
    at.GetMethod("B").Invoke(null, new object[]{"test"});
}

public class A<T>
{
    public static void B(string s)
    {
        Console.WriteLine(s+" "+typeof(T).Name);
    }
}

As a performance optimization you could use reflection to get a delegate for each type which you then can invoke without further reflection.

Type t = typeof(int);
Type at = typeof(A<>).MakeGenericType(t);
Action<string> action = (Action<string>)Delegate.CreateDelegate(typeof(Action<string>), at.GetMethod("B"));
action("test");
Sign up to request clarification or add additional context in comments.

Comments

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.