Programming with Anonymous Types
(Page 1 of 4 )
What is an anonymous type and why is it so important to C# and LINQ? This article answers that question and more. It is excerpted from chapter one of
LINQ Unleashed, written by Paul Kimmel (Sams, 2008; ISBN: 0672329832). This is the first part of a three-part series.
“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.
Next: Understanding Anonymous Types >>
More Database Articles
More By Sams Publishing