Implement an Interface with Generic Methods

Jason N. Gaylord picture Jason N. Gaylord · Aug 28, 2009 · Viewed 103.5k times · Source

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?

Answer

Reed Copsey picture Reed Copsey · Aug 28, 2009

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
    }
}