I want to figure out why "Console.WriteLine(x)" below can directly print the object of a anonymous object?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class program
{
static void Main()
{
var groupA = new[] { 3, 4, 5, 6 };
var groupB = new[] { 6, 7, 8, 9 };
var someInts = from a in groupA
from b in groupB
where a > 4 && b <= 8
select new { a, b, sum = a + b }; // object of Anonymous tyoe
foreach (var x in someInts)
Console.WriteLine(x); // ok
// Console.WriteLine(groupA); // nok
}
}
An anonymous class is created with a ToString()
method that simply displays the properties.
ToString()
is called implicitly by WriteLine()
and many other methods.
For the array, ToString()
is still being called, but it's not overridden so just gives the default text of the fully qualified name.
You wouldn't want an automatic display for an array, since it could contain millions of items. This is unlikely (though possible) for an anonymous type.