Programming with Anonymous Types

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.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 2
November 12, 2009
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

 “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.

Programming with Anonymous Types

This chapter continues by exploring all of the ways you can use anonymous types, paving the way up to anonymous types returned by LINQ queries, stopping at the full explanation of the LINQ query here. You can simply think of the query as a first look at queries with the focus being on the anonymous type itself and what you can do with those types.

Defining Simple Anonymous Types

A simple anonymous type begins with the var keyword, the assignment operator (=), and a non-null initial value. The anonymous type is assigned to the name on the left side of the assignment operator, and the type emitted by the compiler to Microsoft Intermediate Language (MSIL) is determined by the right side of the operator. For instance:

var title = "LINQ Unleashed for C#";

uses the anonymous type syntax and assigns the string value to “LINQ Unleashed for C#”. This code is identical in the MSIL to the following:

string title = "LINQ Unleashed for C#";

This emitted code equality can be seen by looking at the Intermediate Language (IL) with the Intermediate Language Disassembler (ILDASM) utility (see Figure 1.1).

The support for declaring simple anonymous types exists more for completeness and symmetry than utility. In departmental language wars, purists are likely to rail against such use as it adds ambiguity to code. The truth is the type of the data is obvious in such simple use examples and it hardly matters.

Using Array Initializer Syntax

You can use anonymous type syntax for initializing arrays, too. The requirements are that the new keyword must be used. For example, the code in Listing 1.1 shows a simple console application that initializes an anonymous array of Fibonacci numbers. (The anonymous type and array initialization statement are highlighted in bold font.)


Figure 1-1.   Looking at the .locals init statement and the Console::Write(string) statement in the MSIL, it is clear that title is emitted as a string.

LISTING 1.1  An Anonymous Type Initialized with an Array of Integers

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArrayInitializer
{
  class Program
  {
    static void Main(string[] args)
    {
      // array initializer
     
var fibonacci = new int[]{ 1, 1, 2, 3, 5, 8, 13, 21 };
      Console.WriteLine(fibonacci[0]);
      Console.ReadLine();
    }
  }
}

The first eight numbers in the Fibonacci system are defined on the line that begins var fibonacci. Fibonacci numbers start with the number 1 and the sequence is resolved by adding the prior two numbers. (For more information on Fibonacci numbers, check out Wikipedia; Wikipedia is wicked cool at providing detailed facts about such esoterica.)

Even in the example shown in Listing 1.1, you are less likely to get involved in language ambiguity wars if you use the actual type int[] instead of the anonymous type syntax for arrays.

Creating Composite Anonymous Types

Anonymous types really start to shine when they are used to define composite types, that is, classes without the “typed” class definition. Think of this use of anonymous types as defining an inline class without all of the typing. Listing 1.2 shows an anonymous type representing a lightweight person class.

LISTING 1.1  An Anonymous Type Containing Two Fields and Two Properties Without All of the Class Plumbing Typed By the Programmer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ImmutableAnonymousTypes
{
  class Program
  {
    static void Main(string[] args)
    {
      var dena = new {First="Dena", Last="Swanson"};
      //dena.First = "Christine"; // error - immutable
      Console.WriteLine(dena);
      Console.ReadLine();
    }
  }
}

The anonymous type defined on the line starting with var dena emits a class, referred to as a projection, in the MSIL (see Figure 1.2). Although the projection’s name—the class name—cannot be referred to in code, the member elements—defined by the member declarators First and Last—can be used in code and IntelliSense works for all the elements of the projection (see Figure 1.3).

Another nice feature added to anonymous types is the overloaded ToString method. If you look at the MSIL or the output from Listing 1.2, you will see that the field names and field values, neatly formatted, are returned from the emitted ToString method. This is useful for debugging.

Adding Behaviors to Anonymous Composite Types

If you try to add a behavior to an anonymous type at initialization—for instance, by using an anonymous delegate—the compiler reports an error. However, it is possible with a little bending and twisting to add behaviors to anonymous types. The next section shows you how.


Figure 1-2.  Anonymous types save a lot of programming time when it comes to composite types, as shown by the elements emitted to MSIL.


Figure 1-3.  IntelliSense works quite well with anonymous types.

Please check back next week for the second part of this article.

blog comments powered by Disqus
DATABASE ARTICLES

- How To Install DotNetNuke with MySQL
- Manage Projects with SQL Server Management S...
- Query Editing and Regular Expressions with S...
- Using SQL Server Management Studio Tools
- SQL Server Management Studio
- Exporting a MySQL Database to Excel Using OD...
- Controlling Databases with SQL Server 2005 D...
- Using Recovery Models with SQL Server 2005 D...
- Handling Database Properties for the SQL Ser...
- Managing Permissions with the SQL Server 200...
- SQL Server 2005 Database Engine Security
- Administering SQL Server 2005 Database Engine
- Building Applications with Anonymous Types
- A Closer Look at Anonymous Types
- Programming with Anonymous Types

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 11 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials