Sunday, January 20, 2008

Demystifying C# 3.0 - Part 2: Anonymous Types

Source: http://blah.winsmarts.com/2006/05/17/demystifying-c-30--part-2-anonymous-types.aspx

Demystifying C# 3.0 - Part 2: Anonymous Types
Posted on 6/30/2006 @ 8:41 PM in #Vanilla .NET 8 comments 4497 views
In my last blog entry, I had talked about Implicitly typed local variables and the "var" keyword. If you have stumbled across this post through a search engine, or otherwise, I would recommend reading that first.Assuming that you understand "var" - lets dive into part 2 of Demystifying C#3.0 ~ Anonymous Types.In C# 2.0, lets say you wanted to represent a person, you would typically have to write a class as follows -public class Person{ string hairColor ; string skinColor ; int teethCount ;} // I'm obviously taking the shortcut by not creating properties .. anyway, that's besides the point.Well, in LINQ, I could be querying arbitrary groups of my data. When I'm querying "Customers", and the above is a subset of "a customer" - what a royal pain in the rear it would be if I had to first write the structure of my class, before I can use the class? (Duh!). While that sounds like "the thing to do" - you immediately lose the ability to query any arbitrary structures of data at runtime.Enter anonymous types. Now you can represent arbitrary clumps of data, without having to declare their structure first. Here is how.var monster = new {hair="black", skin="green", teethCount=64} ;The above line of code will work even if you do not declare a class called "Person" in advance. This lets you arbitrarily create newer structures to represent your data, without having to define them at "coding time" first.The above line of code simply generates a class under the scenes (you never see it), that looks like as below - class __Anonymous1{ private string _hair = "black"; private string _skin = "green"; private int _teeth = 64;
public string hair {get { return _hair; } set { _hair = value; }} public string skin {get { return _skin; } set { _skin = value; }} public int teeth {get { return _teeth; } set { _teeth = value; }}}Thus this class is an "Anonymous Type" - it has no name, it was generated for you by the C# compiler, so you can represent and hold any arbitrary clump of data, but yes it is a "System.Type".The rationale behind the creation of this was to be able to query for any arbitrary set of data, without having to declare it's structure first. That would be a bit essential for LINQ I'd say ;-).

Labels: , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home