views:

62

answers:

4

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

+2  A: 

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
No, I have this error:'T' is a 'type parameter', which is not valid in the given context
shandu
@shandu - answer updated. You need to supply the generic parameter as well.
Oded
Is it possible to use: class GenericClass<T> where T : MyBaseClass1, MyBaseClass2
shandu
@shandu - No, only one base class.
Oded
@Oded - Can MyBaseClass be interface, and then create MyBaseClass1 and MyBaseClass2 that will be inherent MyBaseClass
shandu
@shandu - You can simply use an interface as a generic type constraint. Read the link in my answer.
Oded
+4  A: 

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  A: 

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 : http://stackoverflow.com/questions/196661/calling-a-static-method-on-a-generic-type-parameter

Shtong
A: 

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
Is it possible to use public class GenericClass<T> where T : SomeType1, SomeType2, new()
shandu
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