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

45,511

Solution 1

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();
    }
}

Solution 2

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

Solution 3

You can do it like this:

public class CommonModel<T> : BaseModel<T>, IMessage where T : ModelClass

Solution 4

class SampleC<T> : IDisposable where T : IDisposable
{
...
}
Share:
45,511
q0987
Author by

q0987

Updated on July 08, 2022

Comments

  • q0987
    q0987 almost 2 years
    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?