Anonymous Types

From time to time you find yourself creating a class only so that you can create a single instance of it, never to use that class again. C# allows you to dispense with all that and combine object initializers and implicitly typed variables, which you learned about back in Chapter 3, to create a class with no name at all: an anonymous type.

You create an instance of an anonymous type with the keyword new, just as you would if you were instantiating an object of a declared class. Instead of passing parameters to a constructor, though, you use braces and define the member fields that you want your anonymous class to contain, like this:

new { Color = "Blue", Size = 13 }

The compiler creates a new class with two member fields. Notice that we’ve capitalized the names of the fields in this declaration, which is contrary to the naming scheme we’ve been using. That’s because these aren’t fields, but properties, which we’ll explain more fully in the next chapter. In brief, properties look like fields to the users of your class, and look like methods to the creator of your class.

This new class contains two properties, Color and Size. Just as with implicitly typed variables, the compiler can determine that Color is a String and Size is an int, and it types them accordingly. And as with implicitly typed variables, you can’t declare the property without assigning it a value, because the compiler needs that value to determine the property’s type.

Of course, the compiler does assign ...

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.