7

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).

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83

4 Answers4

7

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(...);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • No, I have this error: 'T' is a 'type parameter', which is not valid in the given context –  Jul 29 '10 at 08:41
  • @shandu - answer updated. You need to supply the generic parameter as well. – Oded Jul 29 '10 at 08:52
  • Is it possible to use: class GenericClass where T : MyBaseClass1, MyBaseClass2 –  Jul 29 '10 at 10:36
  • @shandu - No, only one base class. – Oded Jul 29 '10 at 10:48
  • @Oded - Can MyBaseClass be interface, and then create MyBaseClass1 and MyBaseClass2 that will be inherent MyBaseClass –  Jul 29 '10 at 12:02
  • @shandu - You can simply use an interface as a generic type constraint. Read the link in my answer. – Oded Jul 29 '10 at 12:34
2

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

Community
  • 1
  • 1
Shtong
  • 1,757
  • 16
  • 30
2

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");
    }
}
Peter
  • 14,221
  • 15
  • 70
  • 110
  • Is it possible to use public class GenericClass where T : SomeType1, SomeType2, new() –  Jul 29 '10 at 10:35
  • No you can only specify one base class (you could create a SomeTypeBase, specify this as the type constraint and let SomeType1 and SomeType3 inherit from this SomeTypeBase class). – Peter Jul 29 '10 at 13:52