How do I define a generic class that implements an interface and constrains the type parameter?

q0987 picture q0987 · Jun 3, 2011 · Viewed 40.8k times · Source
class Sample<T> : IDisposable // case A
{
    public void Dispose()
    {
        throw new NotImplementedException();
    }
}

class SampleB<T> where T : IDisposable // case B
{
}

class SampleC<T> : IDisposable, T : IDisposable // case C
{
    public void Dispose()
    {
        throw new NotImplementedException();
    }
}

Case C is the combination of case A and case B. Is that possible? How to make case C right?

Answer

dtb picture dtb · Jun 3, 2011

First the implemented interfaces, then the generic type constraints separated by where:

class SampleC<T> : IDisposable where T : IDisposable // case C
{        //                      ↑
    public void Dispose()
    {
        throw new NotImplementedException();
    }
}