Tutorial :Call a method of type parameter



Question:

Is there any way to do code such this:

class GenericClass<T>  {      void functionA()      {          T.A();      }  }  

Or, how to call a function of type parameter (type is some my custom class).


Solution:1

To call a method of a generic type object you have to instantiate it first.

public static void RunSnippet()  {      var c = new GenericClass<SomeType>();  }    public class GenericClass<T> where T : SomeType, new()  {      public GenericClass(){          (new T()).functionA();      }     }    public class SomeType  {      public void functionA()      {          //do something here          Console.WriteLine("I wrote this");      }  }  


Solution:2

Re:

T.A();

You can't call static methods of the type-parameter, if that is what you mean. You would do better to refactor that as an instance method of T, perhaps with a generic constraint (where T : SomeTypeOrInterface, with SomeTypeOrInterface defining A()). Another alternative is dynamic, which allows duck-typing of instance methods (via signature).

If you mean that the T is only known at runtime (as a Type), then you would need:

typeof(GenericClass<>).MakeGenericType(type).GetMethod(...).Invoke(...);  


Solution:3

I think you are looking for generic type constraints:

class GenericClass<T> where T : MyBaseClass  {      void functionA<T>(T something)      {          something.A();      }  }  

In terms of the code you posted - in order to call something on T, you will need to pass it as a parameter to functionA. The constraint you use will have to ensure that any T has an A method that can be used.


Solution:4

I understand from your code that you want to call a type parameter static method, and that's just impossible.

See here for more info : Calling a static method on a generic type parameter


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »