2

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();
}
Oded
  • 489,969
  • 99
  • 883
  • 1,009
pt12lol
  • 2,332
  • 1
  • 22
  • 48

2 Answers2

8

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();
}
Community
  • 1
  • 1
Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90
2

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009