Free mag vol1 | Page 486

CHAPTER 11  ADVANCED C# LANGUAGE FEATURES The output will look similar to the following: ***** Fun with Anonymous Types ***** obj is an instance of: <>f__AnonymousType0`3 Base class of <>f__AnonymousType0`3 is System.Object obj.ToString() = { Color = Bright Pink, Make = Saab, CurrentSpeed = 55 } obj.GetHashCode() = -439083487 First, notice that in this example, the myCar object is of type <>f__AnonymousType0`3 (your name may differ). Remember that the assigned type name is completely determined by the compiler and is not directly accessible in your C# code base. Perhaps most important, notice that each name/value pair defined using the object initialization syntax is mapped to an identically named read-only property and a corresponding private read-only backing field. The following C# code approximates the compiler-generated class used to represent the myCar object (which again can be verified using ildasm.exe): internal sealed class <>f__AnonymousType0<j__TPar, j__TPar, j__TPar> { // Read-only fields. private readonly j__TPar i__Field; private readonly j__TPar i__Field; private readonly j__TPar i__Field; // Default constructor. public <>f__AnonymousType0(j__TPar Color, j__TPar Make, j__TPar CurrentSpeed); // Overridden methods. public override bool Equals(object value); public override int GetHashCode(); public override string ToString(); } // Read-only properties. public j__TPar Color { get; } public j__TPar CurrentSpeed { get; } public j__TPar Make { get; } The Implementation of ToString() and GetHashCode() All anonymous types automatically derive from System.Object and are provided with an overridden version of Equals(), GetHashCode(), and ToString(). The ToString() implementation simply builds a string from each name/value pair. For example: 426