Click to Rate and Give Feedback
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
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.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Returning anonymous types from methods and casting to anonymous types      Oran Dennison ... Medo   |   Edit   |   Show History

"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

Returning anonymous types from methods and casting to anonymous types: lead to be poor quality code      Luca Minudel ... Livery   |   Edit   |   Show History

The need to return anonymous type can emerge e.g. while refactoring long methods with Linq code: trying to extract some Linq code into a new method

While the trick to return anonymous types is interesting by a technological point of view, it do lead to poor quality code (hard to read, error prone).

When I need to return an anonymous type, I do declare and use a real type with just automatic properties and without constructors and use that.
It work fine even with Linq2Sql (the Sql execution plan will not change because of the refactoring).
The resulting code is easy to read/understand and is type-safe.


IMHO The difference between a good programmer and a bad one is that a good programmer always strives to do things the straight way while a bad programmer feels smart when he discover and use dirty tricks

Edit: I doubt that was a useful comment. Using anonymous types in-fact reduces code thus making programmers more efficent. Creating a type class for each Linq query is definately unruly. Gawd forbid you needed to update that code. Now you have to make changes everywhere you use that typed class versus just changing the Linq query. BTW, anonymous types are strongly typed. Its called <>f__Anonymous....

Tags What's this?: Add a tag
Flag as ContentBug
Returning anonymous types from methods can be powerful especially with CompiledQuery.Compile      eldoran   |   Edit   |   Show History
The below code is what I came up with when I was trying to figure out how to iterate anonymous types from a different class. This idea is useful as it combines CompiledQuery.Query and multiple return tables. Basically this could be done with a view, or a stored procedure; but the challenge I had was doing it all through LINQ.
It should be pretty self-explanatory (I think) once you figure it out. For ease of use for this example, I put both my static Main and GetItems() in the same class MyTest.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data.Linq;

namespace MyNamespace

{

public sealed class MyTest

{

public static void Main()

{

MyContext context = new MyContext();

var output = GetItems();

foreach (var item in output.ToList())

{

Console.WriteLine(item);

}

Console.Read();

}

/// <summary>

/// Returns an iterator for an anonymous method

/// </summary>

/// <returns></returns>

public static IEnumerable<Object> GetItems()

{

var returnCode =

CompiledQuery.Compile((MyContext dc) =>

from p in dc.Table1

join f in dc.Table2 on p.ID equals f.table1ID

select new

{

p,

f

});

var output = returnCode;

MyContext context = new MyContext();

foreach (var o in output.Invoke(context))

{

yield return o.f.table1ID;

yield return o.p.ID;

}

}

}

}

Tags What's this?: Add a tag
Flag as ContentBug
CORRECTION - compiler determined type      Justin M James   |   Edit   |   Show History
"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."

This is not correct. In fact, the property names play into this as well, otherwise anonymous types would be dangerous. Look at this code:

var

type1 = new {lastName = "James", email = "junk@domain.com", age = 30};

var

type2 = new {companyName = "TechRepublic", domainName = "www.techrepublic.com", yearsInBusiness = 20 };

var

type1SecondVar = new { lastName = "Washington", email = "firstpres@whitehouse.gov", age = 200 };

Console

.WriteLine(type1.GetType());

Console

.WriteLine(type2.GetType());

Console

.WriteLine(type1SecondVar.GetType());

Console

.ReadLine();

It produces the following output:

<>f__AnonymousType0`3[System.String,System.String,System.Int32]
<>f__AnonymousType1`3[System.String,System.String,System.Int32]
<>f__AnonymousType0`3[System.String,System.String,System.Int32]

Clearly, the property names play into whether or not the compiler treats them as the same type.
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker