Search code examples
c#genericstype-parameter

Call a method of type parameter


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

  • 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");
        }
    }