I am reading Jon skeet amazing book "C # in depth (3d version)" right now. I am stuck on p.99, dealing with a lack of contraception for generics.
class TestGenericVariance
{
public static void Main(string[] args)
{
IComparer<IShape> x =new AreaComparer();
List<Circle> circles = new List<Circle>();
circles.Add(new Circle());
circles.Add(new Circle());
circles.Sort(x);
}
public interface IShape
{
}
public class Circle : IShape
{
}
public class AreaComparer : IComparer<IShape>
{
public int Compare(IShape x, IShape y)
{
return 0;
}
}
}
This code does not work because the Sort method expects
IComparer<Circle>
as the type of parameter.
One of p.99's proposed works is to make the AreaComparer class universal:
class AreaComparer<T> : IComparer<T> where T : IShape
And then modify the non-generic AreaComparer set to get a generic movie:
class AreaComparer : AreaComparer<IShape>
In C # 2, the code does not compile because the Sort method on circles is still waiting
IComparer<Circle>
Did I miss something?
Note: if I go to:
class AreaComparer : AreaComparer<Circle>
The first line of code in the main method requests an explicit conversion form
Thank you all for your help.
source
share