0

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
    }
}
webprogrammer
  • 2,393
  • 3
  • 21
  • 27
Firmament
  • 3
  • 4
  • 4
    Does this answer your question? [How does ToString on an anonymous type work?](https://stackoverflow.com/questions/16794275/how-does-tostring-on-an-anonymous-type-work) – mbshambharkar Mar 21 '20 at 13:00

2 Answers2

2

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.

Jasper Kent
  • 3,546
  • 15
  • 21
0

An anonymous class is just like any other class, except that it is implicit. That means it (like any other class) can contain propeties or members, in your case integers as part of its internals. so

Console.WriteLine(x); // makes sense. x is just an integer

In theory if you take any explicit class and evaluate its .ToString() you get its name. So in theory if you did groupA.ToStrint() you should get "Anonymous.abjdhjNxx1" or whatever. You can actually breakpoint that line and add a watch to your groupA variable to see that. It's still just a variable, and it's still type safe, you just never know what the "name" of your type will be, since the runtime intermediate environment makes it up as it goes along. However, as implied here, it's gibrish, so the good people of Microsoft decided not to show us that directly. which is why

Console.WriteLine(groupA); // not ok

if you want, you can still do

Console.WriteLine(groupA.GetType().Name);

but I can't imagine why you would want to do that, because as stated before it's gibrish

LongChalk
  • 783
  • 8
  • 13