C# Programming Guide
Anonymous Types (C# Programming Guide)

Updated: July 2008

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. The type name is generated by the compiler and is not available at the source code level. The type of the properties is inferred by the compiler. The following example shows an anonymous type being initialized with two properties called Amount and Message.

var v = new { Amount = 108, Message = "Hello" };

Anonymous types are typically used in the select clause of a query expression to return a subset of the properties from each object in the source sequence. For more information about queries, see LINQ Query Expressions (C# Programming Guide).

Anonymous types are created by using the new operator with an object initializer. For more information about object initializers, see Object and Collection Initializers (C# Programming Guide).

Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed. An anonymous type cannot be cast to any interface or type except for object.

The most common scenario is to initialize an anonymous type with some properties from another type. In the following example, assume a class that is named Product that includes Color and Price properties together with several other properties that you are not interested in. Products is a collection of Product objects. The anonymous type declaration starts with the new keyword. It initializes a new type that uses only two properties from Product. This causes a smaller amount of data to be returned in the query.

If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the property being used to initialize them. You must provide a name to a property that is being initialized with an expression.

C#
var productQuery = 
    from prod in products
    select new { prod.Color, prod.Price };

foreach (var v in productQuery)
{
    Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}

When an anonymous type is assigned to a variable, that variable must be initialized with the var construct. This is because only the compiler has access to the underlying name of the anonymous type. For more information about var, see Implicitly Typed Local Variables (C# Programming Guide).

Anonymous types are reference types that derive directly from object. The compiler gives them a name although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.

If two or more anonymous types have the same number and type of properties in the same order, the compiler treats them as the same type and they share the same compiler-generated type information.

An anonymous type has method scope. To pass an anonymous type, or a collection that contains anonymous types, outside a method boundary, you must first cast the type to object. However, this defeats the strong typing of the anonymous type. If you must store your query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.

Anonymous types cannot contain unsafe types as properties.

Because the Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode of the properties, two instances of the same anonymous type are equal only if all their properties are equal.

Date

History

Reason

July 2008

Added information about cast restrictions to introductory text and Remarks section.

Information enhancement.


How to: Return Subsets of Element Properties in a Query (C# Programming Guide)

MSDN Library
Development Tools and Languages
Visual Studio 2008
Visual Studio
Visual C#
C# Programming Guide
Classes and Structs (C# Programming Guide)
Anonymous Types (C# Programming Guide)
Tags: 
 
Community Content
Returning anonymous types from methods and casting to anonymous types   Last Edit 7:07 AM by Balamurugan J   

"To pass an anonymous type, or a collection that contains anonymous types, outside a method boundary, you must first cast the type to object."

This isn't entirely true. Consider this helper method:

public static List<T> ListOfType<T>(this T type)
{
return new List<T>();
}

This allows you to write:

var v = new { Amount = 108, Message = "Hello" };
var listOfV = ListOfType(v);
listOfV.Add(v);

I just passed a new strongly-typed List<some_anonymous_type> out of a method without casting it to object.

You can also cast object to an anonymous type using the following helper method:

T Cast<T>(object obj, T type)
{
return (T)obj;
}

So even if you return the anonymous type from a method by casting to object, you can use it strongly typed like this:

var v = Cast(ThisReturnsAnonymousTypeAsObject(), new { Amount = 0, Message = "" });
if(v.Message == "Hello") ...

See "Can't return anonymous type from method? Really?" for more details:

http://tomasp.net/blog/cannot-return-anonymous-type-from-method.aspx

Tags: