Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Tools

Anonymous Types in the .NET Framework



In Visual Studio 2008, the C# compiler supports some new and quite interesting features. Some of them are just a pinch of syntactic sugar to save the developer the burden of some repetitive and imperative tasks such as creating quite simple getters and setters for class properties. Some other features, instead, add new capabilities to the language and the .NET programming platform as a whole. In this regard, the ASP.NET platform is no exception. In this article, I briefly discuss anonymous types with the goal of delimiting clearly their realm and avoid misuse.

To start off, what's an "anonymous" type and how is it different from a regular "known" type? Quite simply, an anonymous type is an unnamed type. So the only difference with a regular known .NET type is merely in the name. For the Common Language Runtime (CLR), in fact, anonymous and named types are exactly the same entity. Anonymous types can be used in a variety of scenarios, but they have been introduced primarily to support LINQ queries throughout the .NET and ASP.NET platform.

Here's what an anonymous type looks like:

var person = new { 
    FirstName="Nancy", 
    LastName="Davolio", 
    Age=28 
};

Essentially, an anonymous type enables you to create an instance of an object without writing or importing a definition for the object type. At a quick look, it looks similar to JavaScript objects, in turn based on associative arrays; but it's only the first look.

In the .NET Framework, the language compiler generates a class on the fly. However, the class has no human-readable and usable name and it inherits directly from System.Object. The developer may get to know the name of the dynamically generated class using the GetType method, but this piece of information is hardly useful. For example, if invoke te method GetType on the person variable defined earlier, here's what you obtain:


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

Is this a piece of information you reckon useful? That's why these types are referred to as anonymous types. You should note that the name of the anonymous type is not strictly related to value or properties names, but it entirely compiler generated. So it may be different from compilation to compilation. As you can see, this is an even better reason not to rely on the name of an anonymous type in your coding.

Just because there's no class definition, the list of members includes only the properties you specify when you declare the object. The type of these properties is inferred and is then reported in the hidden type name.

As mentioned, anonymous types exist mostly (only?) to serve LINQ queries, but is there some other scenario where they can be helpful? In reality, not many.

Anonymous types work well in local scenarios where you need a temporary object to contain logically-related values. Needless to say, if you have other needs such as fields or methods, then just stick to named types and forget about anonymous types. Anonymous types can't be used in any situation where a type is expected. For example, you can hardly pass an anonymous type as a named type is expected and there's no syntax that lets you specify an anonymous type. The best you can do is trying to use an anonymous type where an Object is expected.

void Foo(object o)
{ ... }

However, within the method you can't address any of the properties of the anonymous type. All that you can do is using reflection.

void Foo(object o)
{
    Type t = o.GetType();
    PropertyInfo pi = t.GetProperty("FirstName");
    string v = pi.GetValue(o, null) as string;
    Console.WriteLine(v);
    return;
}

In this case, it will work. But is it worth the effort? Using anonymous types across methods is strongly discouraged. Consider that two objects are of the same anonymous type only if they live in the same assembly, use the same properties with the same names and types and listed in the same order.

The C# and Visual Basic .NET compilers needed anonymous types as a foundation for their LINQ support. Besides this, avoid anonymous types.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.