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

C#GenericsInheritanceConstraints

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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 - C#

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

Solution 3 - C#

You can do it like this:

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

Solution 4 - C#

class SampleC<T> : IDisposable where T : IDisposable
{
...
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionq0987View Question on Stackoverflow
Solution 1 - C#dtbView Answer on Stackoverflow
Solution 2 - C#DuckMaestroView Answer on Stackoverflow
Solution 3 - C#MoumitView Answer on Stackoverflow
Solution 4 - C#elder_georgeView Answer on Stackoverflow