Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling method in template in C#

Tags:

c#

I tried using method (foo2) from the template method (foo1) and compiler said that he doesn't know this method (foo2) which belongs to that class (T).

What is the right syntax, which compiler accept it?

private void foo1<T>(T instance)
{
    instance.foo2();
}
like image 917
pt12lol Avatar asked Dec 03 '25 17:12

pt12lol


2 Answers

You should create constraint on generic type like in the code snippet below:

private void foo1<T>(T instance) where T : IFoo
{ 
    instance.foo2(); 
}

interface IFoo
{
    void foo2();
}

Which defines, that closed generic types can only be derived from IFoo interface. But why don't you stick with non-generic version like given below?

private void foo1(IFoo instance) 
{ 
    instance.foo2(); 
}

interface IFoo
{
    void foo2();
}
like image 122
Ilya Ivanov Avatar answered Dec 06 '25 07:12

Ilya Ivanov


You are using a generic method without any constraint on the generic type.

This means that it can be any object. The compiler is complaining because most objects do not have a foo2 method.

You need to constrain the generic type to a type that has a foo2() method if you want to be able to invoke that method on the generic parameter.

Alternatively, don't use generics but pass in the abstract type that has foo2 defined on it.

like image 30
Oded Avatar answered Dec 06 '25 08:12

Oded