New Orcas Language Feature: Anonymous Types
page 6 of 10
by Scott Guthrie
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 37180/ 50

Declaring Anonymous Types

Now that we've introduced the "var" keyword, we can start to use it to refer to anonymous types.

Anonymous types in C# are defined using the same object initializer syntax I covered in my first blog post in this language series.  The difference is that instead of declaring the type-name as part of the initialization grammar, when instantiating anonymous types you instead just leave the type-name blank after the "new" keyword:

Figure 7

The compiler will parse the above syntax and automatically define a new standard CLR type that has 4 properties.  The types of each of the 4 properties are determined based on the type of the initialization values being assigned to them (for example: in the sample above the "Id" property is being assigned an integer - so the compiler will generate the property to be of type integer). 

The actual CLR name of the anonymous type will automatically be generated by the C# compiler.  The CLR itself actually doesn't know the difference between an anonymous type and a named type - so the runtime semantics of the two are absolutely identical.  Bart De Smet has a good blog post here that details this if you want to see the exact class name pattern and IL generated. 

Note above how when you type "product." on the anonymous type, you still get compile-time checking and full intellisense within Visual Studio.  Notice also how the intellisense description indicates it is an "AnonymousType" - but still provides full declaration information of the properties (this is the text circled in red).


View Entire Article

User Comments

No comments posted yet.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-28 9:10:36 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search