CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
class SomeClass
{
// Define a set of private member variables...
// Make a property for each member variable...
// Override ToString() to account for key member variables...
}
// Override GetHashCode() and Equals() to work with value-based equality...
As you can see, it is not necessarily so simple. Not only do you need to author a fair amount of code,
but you have another class to maintain in your system. For temporary data such as this, it would be
useful to whip up a custom data type on the fly. For example, let’s say that you need to build a custom
method that receives a set of incoming parameters. You would like to take these parameters and use
them to create a new data type for use in this method scope. Further, you would like to quickly print out
this data using the typical ToString() method and perhaps use other members of System.Object. You
can do this very thing using anonymous type syntax.
Defining an Anonymous Type
When you define an anonymous type, you do so by making use of the var keyword (see Chapter 3) in
conjunction with object initialization syntax (see Chapter 5). We must use the var keyword because the
compiler will automatically generate a new class definition at compile time (and we never see the name
of this class in our C# code). The initialization syntax is used to tell the compiler to create private backing
fields and (read-only) properties for the newly created type.
To illustrate, create a new Console Application named AnonymousTypes. Now, add the following
method to your Program class, which composes a new type, on the fly, using the incoming parameter
data:
static void BuildAnonType( string make, string color, int currSp )
{
// Build anon type using incoming args.
var car = new { Make = make, Color = color, Speed = currSp };
// Note you can now use this type to get the property data!
Console.WriteLine("You have a {0} {1} going {2} MPH",
car.Color, car.Make, car.Speed);
// Anon types have custom implementations of each virtual
// method of System.Object. For example:
Console.WriteLine("ToString() == {0}", car.ToString());
}
You can call this method from Main(), as expected. However, do note that an anonymous type can
also be created using hard-coded values, as seen here:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Anonymous Types *****\n");
// Make an anonymous type representing a car.
var myCar = new { Color = "Bright Pink", Make = "Saab", CurrentSpeed = 55 };
424