Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement an Interface with Generic Methods

I'm drawing a blank on this one and can't seem to find any previous example that I wrote. I'm trying to implement a generic interface with a class. When I implement the interface I think something isn't working right because Visual Studio continually produces errors saying that I'm not implmenting all of the methods in the Generic Interface.

Here's a stub of what I'm working with:

public interface IOurTemplate<T, U> {     IEnumerable<T> List<T>() where T : class;     T Get<T, U>(U id)         where T : class         where U : class; } 

So what should my class look like?

like image 593
Jason N. Gaylord Avatar asked Aug 28 '09 02:08

Jason N. Gaylord


People also ask

Can a generic class implement an interface?

Only generic classes can implement generic interfaces. Normal classes can't implement generic interfaces.

Can we use generics with interface in Java?

If a class implements generic interface, then class must be generic so that it takes a type parameter passed to interface.


2 Answers

You should rework your interface, like so:

public interface IOurTemplate<T, U>         where T : class         where U : class {     IEnumerable<T> List();     T Get(U id); } 

Then, you can implement it as a generic class:

public class OurClass<T,U> : IOurTemplate<T,U>         where T : class         where U : class {     IEnumerable<T> List()     {         yield return default(T); // put implementation here     }      T Get(U id)     {          return default(T); // put implementation here     } } 

Or, you can implement it concretely:

public class OurClass : IOurTemplate<string,MyClass> {     IEnumerable<string> List()     {         yield return "Some String"; // put implementation here     }      string Get(MyClass id)     {          return id.Name; // put implementation here     } } 
like image 145
Reed Copsey Avatar answered Oct 01 '22 04:10

Reed Copsey


I think you probably want to redefine your interface like this:

public interface IOurTemplate<T, U>     where T : class     where U : class {     IEnumerable<T> List();     T Get(U id); } 

I think you want the methods to use (re-use) the generic parameters of the generic interface in which they're declared; and that you probably don't want to make them generic methods with their own (distinct from the interface's) generic parameters.

Given the interface as I redefined it, you can define a class like this:

class Foo : IOurTemplate<Bar, Baz> {     public IEnumerable<Bar> List() { ... etc... }     public Bar Get(Baz id) { ... etc... } } 

Or define a generic class like this:

class Foo<T, U> : IOurTemplate<T, U>     where T : class     where U : class {     public IEnumerable<T> List() { ... etc... }     public T Get(U id) { ... etc... } } 
like image 33
ChrisW Avatar answered Oct 01 '22 04:10

ChrisW