The New Anonymous Types Feature in C# 3.0

At the PDC 2005, on the eve of the release of C# 2.0 (C# Whidbey), Microsoft previewed its plans for C# 3.0 (C# Orcas). Along with a list of fantastic new features such as Language Integrated Query (LINQ), Redmond also described a new feature called anonymous types. This article takes a deeper look at anonymous types.

Anonymous Types Defined

The C# 3.0 specifications describe anonymous types as tuple types automatically inferred and created from object initializers. Before you can fully understand the meaning of this definition, you need to understand the term "object initializer," which is the basis of the anonymous types feature.

An object initializer specifies values from one or more fields or properties of an object. That means you specify a set of properties for an object through a series of assignments, such as {a = 10, b = 20}, and an object is assigned these properties. In other words, an anonymous type is one that previously did not exist and was not defined explicitly in code.

Note: The compiler creates the anonymous type at compile time and not run time.

You can see this class in the disassembly through ILDASM (the IL Disassembler):

At compile time, the compiler creates a new (anonymous) type with properties inferred from the object initializer. Hence, the new type will have the properties Name and Price. The Get and Set methods, as well as the corresponding private variables to hold these properties, are generated automatically. At run time, an instance of this type is created and the properties of this instance are set to the values specified in the object initializer.

C# Internals

You might be surprised to learn that you define only the names of the properties and their values and C# 3.0 automatically creates a class from them. How does it do that? Check out how the compiler processes your request.