Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

Blog Directory
Blogging Fusion Blog Directory
Web Directory
Blog Directory
EatonWeb Blog Directory
GeekySpeaky: Submit Your Site!
Blog Directory
blogarama - the blog directory
Bloglisting.net - The internets fastest growing blog directory
Blogio.net blog directory
Free Blog Directory
blog search directory
Software Blogs
RSSMicro FeedRank Results
On our way to 1,000,000 rss feeds - millionrss.com
Listed in LS Blogs the Blog Directory and Blog Search Engine
blog directory
Link With Us - Web Directory
Web Blogs Directory Add Your Blog.com

Certificates

Links

Social

C# and anonymous types

One cool feature of C# 3.0 is support of anonymous types. Let's suppose we have to create some data structure and we need this structure in one place in one method. This far we had to create a new private class or structure. With anonymous types we don't have to define new type - we can create it on the run.

Let's create a simple anonymous type for rectangle. The code is as follows and let's suppose it makes some calculations using dimensions of object.


...

var rectangle = new { Width=x, Height=y };

...

return density;


As we can see there is no type specified for rectangle. Instead type we have plain definition of object. This definition is also supported by IntelliSense.

Anonymous types are supported by IntelliSense

If we look at previous picture we can see that our new variable has all the properties that objects have. It is inherited from object class. Let's see now what compiler produced us.

Structure of anonymous type

As we can see there is new type called <>f__AnonymousType0`2 defined. This is our rectangle. The other classes are not able to inherit from our rectangle and also it is not possible to recreate this type in code again. This new type is created after compilation and it doesn't exist until compilation.

Anonymous types may be very useful if we need some temporary structures to organize our data better. Anonymous types must be used very carefully because otherwise they may mess up your code and make readability worst. Therefore it is good idea to use anonymous types carefully.

Comments

No Comments

Leave a Comment

(required) 

(required) 

(optional)

(required)