Get a generic method and invoke it C# with Example



Get a generic method and invoke it C# with Example

Let's say you have class with generic methods. And you need to call its functions with reflection. 
public class Sample 
{ 
public void GenericMethod() 
{ 
// ... 
} 
public static void StaticMethod() 
{ 
//... 
} 
} 
Let's say we want to call the GenericMethod with type string. 
Sample sample = new Sample();//or you can get an instance via reflection 
 

MethodInfo method = typeof(Sample).GetMethod("GenericMethod"); 
MethodInfo generic = method.MakeGenericMethod(typeof(string)); 
generic.Invoke(sample, null);//Since there are no arguments, we are passing null 
For the static method you do not need an instance. Therefore the first argument will also be null. 
MethodInfo method = typeof(Sample).GetMethod("StaticMethod"); 
MethodInfo generic = method.MakeGenericMethod(typeof(string)); 
generic.Invoke(null, null); 

0 Comment's

Comment Form

Submit Comment