When implementing an interface in Generic, why it is not must implement the methods

When implementing an interface in Generic, why it is not must implement the methods

public interface IMyTest<T>
{
    T Add(T i, T j);
}

public class MyContainer<T> where T : IComparable<T>, IMyTest<T> 
{

}
Jon Skeet
people
quotationmark

You're not implementing the interface. You're saying that the type argument supplied for the type parameter T must itself implement the interface. That's what the where T part means - it's specifying constraints on T.

This means that in your MyContainer class you can use the members of the interface:

public class MyContainer<T> where T : IComparable<T>, IMyTest<T> 
{
    public T SumBiggestAndSmallest(IEnumerable<T> items)
    {
        var ordered = items.OrderBy(x => x)
                           .ToList();
        return ordered.First().Add(ordered.First(), ordered.Last());
    }
}

(It's unclear why your Add method takes two T values, as well as being an instance method, but that's a different matter.)

Without the constraints on T, you wouldn't have an Add method to call.

people

See more on this question at Stackoverflow