-2

Can you explain the behavior of why this code produces this result?

var person = new { name = "George", age = 30};
WriteLine(person);

And Output is:

{ name = "George", age = 30}

Johnson
  • 401
  • 5
  • 14

1 Answers1

3

WriteLine(object) implicitly calls ToString() on the underlying object. The method is virtual, meaning it can be overridden by derived types.

Anonymous types override object.ToString to show their properties and values. The compiler generates the overridden method, and it can't be changed at compile-time or run-time.

D Stanley
  • 149,601
  • 11
  • 178
  • 240