Question

In the code below i am targetting the .NET 2.0 Framework.

I can pass a Programmer (derived) object to the Compare method which expects a Person (base class)

But since a Programmer IS A Person (simple OO concept) i claim that in .NET 4.0 the 'in' keyword in the IComparable interface declaration is 'overkill' :)

Before i write an email to Microsoft about them removing the in keyword please try to convince me otherwise :)

class Program
{
    static void Main(string[] args)
    {
        var person = new Person();

        var test = person.CompareTo(new Programmer());
    }
}

internal class Person : IComparable<Person>
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int CompareTo(Person other)
    {
        return this.Id - other.Id;
    }
}

class Programmer : Person
{
    public string ProgrammingLanguage { get; set; }
}
Was it helpful?

Solution

Co- and contravariance is not about the types you pass into the methods. It is about the generic interfaces that contain the methods.

With in the following code is legal:

IComparable<Person> foo = ...;
IComparable<Programmer> bar = foo;

Without the in it would be illegal.

OTHER TIPS

By the Liskov substitution principle, if an IComparer<> implementation can compare Person instances, then it can compare objects of types derived from Person. The in keyword allows you to use an IComparer<Person> comparer to compare objects of type MyPerson (derived from Person). An example use case is a comparer that orders Person instances by name for use in a SortedList<Person>; where the contravariant interface also allows the same comparer to be used with SortedList<MyPerson>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top