3

I've created a struct named Point and a List of such points:

var myPoints = new List<Point> {
    new Point() {Col = 3, Row = 2},
    new Point() {Col = 2, Row = 4},
    new Point() {Col = 5, Row = 4},
};

When I try to print them using ForEach() method, I cannot pass a method group there: myPoints.ForEach(Console.WriteLine); gives a compile time error saying that a method with void WriteLine(Point) signagure is expected. If I use a lambda expression or change Point to be a class instead of struct it works just perfectly.

Why does it happen even though there's always an implicit conversion from any value type to object via boxing -- and the method Console.WriteLine(object) should therefore be chosen?

Thank you!

Mikhail Dudin
  • 459
  • 5
  • 15
  • 2
    Variance works only on reference types. It is not supported for structs because the conversion requires boxing, which is not representation preserving. This is similar to when you have an function taking a double but you got a list of ints. Even though the compiler will insert an implicit conversion for you, it doesn't mean int is truly like a double to the jitter or the runtime. One is 4 bytes the other 8 bytes. – Mike Zboray Feb 21 '15 at 01:20
  • @mikez: IMHO, that comment, along with more detail from the C# specification describing the applicable conversion rules, would make a nice answer. :) – Peter Duniho Feb 21 '15 at 01:43

0 Answers0