M_B216
M_B216

Reputation: 103

Multiple inheritance frome more than one interface

Let me have a template class ( class Entry<T>), I want to make this class inherit from tow interfaces (IComparable<T> and IEquatable<T>), I've tried this:

class Entry<T> where T : IComparable<T>, IEquatable<T>
{
 /* Whatever in the class */
}

and I've tried the next code:

class Entry<T> : IEquatable<T>, where T : IComparable<T>
{
 /* Whatever in the class */
}

but non of them worked correctly, I don't know Why, anyone Can help me to know how I can use multiple interfaces inheritance?

Upvotes: 1

Views: 173

Answers (1)

User 12345678
User 12345678

Reputation: 7804

Use the following signature to implement both IEquatable<T> and IComparable<T>:

public class Entry<T> : IComparable<T>, IEquatable<T>
{
    public int CompareTo(T other)
    {
        //compare logic... 
    }

    public bool Equals(T other)
    {
        return CompareTo(other) == 0;
    }
}

Your first example is using the where clause to form a generic type constraint that says "only accept a type argument that implements IComparable<T> and IEquatable<T>".

Your second example has invalid syntax. It looks like you're trying to say "The T IEquatable<T> takes must implement IComparable<T>". If you want to do that then you must also constrain T in class Entry<T>.

Upvotes: 2

Related Questions