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?
Only generic classes can implement generic interfaces. Normal classes can't implement generic interfaces.
If a class implements generic interface, then class must be generic so that it takes a type parameter passed to interface.
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 } }
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... } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With