Programming with Anonymous Types in C#
- "Begin at the beginning and go on till you come to the end: then stop."
- —Lewis Carroll, from Alice's Adventures in Wonderland
Finding a beginning is always a little subjective in computer books. This is because so many things depend on so many other things. Often, the best we can do is put a stake in the ground and start from that point. Anonymous types are our stake.
Anonymous types use the keyword var. Var is an interesting choice because it is still used in Pascal and Delphi today, but var in Delphi is like ByRef in Visual Basic (VB) or ref in C#. The var introduced with .NET 3.5 indicates an anonymous type. Now, our VB friends are going to think, "Well, we have had variants for years; big deal." But var is not a dumbing down and clogging up of C#. Anonymous types are something new and necessary.
Before looking at anonymous types, let's put a target on our end goal. Our end goal is to master LINQ (integrated queries) in C# for objects, Extensible Markup Language (XML), and data. We want to do this because it's cool, it's fun, and, more important, it is very powerful and expressive. To get there, we have to start somewhere and anonymous types are our starting point.
Anonymous types quite simply mean that you don't specify the type. You write var and C# figures out what type is defined by the right side, and C# emits (writes the code), indicating the type. From that point on, the type is strongly defined, checked by the compiler (not at runtime), and exists as a complete type in your code. Remember, you didn't write the type definition; C# did. This is important because in a query language, you are asking for and getting ad hoc types that are defined by the context, the query result. In short, your query's result might return a previously undefined type.
An important concept here is that you don't write code to define the ad hoc types—C# does—so, you save time by not writing code. You save design time, coding time, and debug time. Microsoft pays that cost. Anonymous types are the vessel that permit you to use these ad hoc types. By the time you are done with this chapter, you will have mastered the left side of the operator and a critical part of LINQ.
In addition, to balance the book, the chapters are laced with useful or related concepts that are generally helpful. This chapter includes a discussion on generic anonymous methods.
Understanding Anonymous Types
Anonymous types defined with var are not VB variants. The var keyword signals the compiler to emit a strong type based on the value of the operator on the right side. Anonymous types can be used to initialize simple types like integers and strings but detract modestly from clarity and add little value. Where var adds punch is by initializing composite types on the fly, such as those returned from LINQ queries. When such an anonymous type is defined, the compiler emits an immutable—read-only properties—class referred to as a projection.
Anonymous types support IntelliSense, but the class should not be referred to in code, just the members.
The following list includes some basic rules for using anonymous types:
- Anonymous types must always have an initial assignment and it can't be null because the type is inferred and fixed to the initializer.
- Anonymous types can be used with simple or complex types but add little value to simple type definitions.
- Composite anonymous types require member declarators; for example, var joe = new {Name="Joe" [, declaratory=value, ... ]}. (In the example, Name is the member declaratory.)
- Anonymous types support IntelliSense.
- Anonymous types cannot be used for a class field.
- Anonymous types can be used as initializers in for loops.
- The new keyword can be used and has to be used for array initializers.
- Anonymous types can be used with arrays.
- Anonymous types are all derived from the Object type.
- Anonymous types can be returned from methods but must be cast to object, which defeats the purpose of strong typing.
- Anonymous types can be initialized to include methods, but these might only be of interest to linguists.
The single greatest value and the necessity of anonymous types is they support creating single-use elements and composite types returned by LINQ queries without the need for the programmer to fully define these types in static code. That is, the designers can focus significantly on primary domain types, and the programmers can still create single-use anonymous types ad hoc, letting the compiler write the class definition.
Finally, because anonymous types are immutable—think no property setters—two separately defined anonymous types with the same field values are considered equal.