C Sharp 3.0 and Anonymous Types
Posted on 8/12/2007 9:46:20 AM
in #C Sharp
Hi,
I have been using the new Orcas Beta 2 and dot net frame work for some time now and have been really enjoying the features of the C Sharp. One of the new features also includes Anonymous types. It first thought there might not be much use of this feature and will only be a syntactic sugar for us. But after playing with Dot net framework 3.5 for a while I understand the importance of this new feature. Let me also tell that this feature will be most useful in case you are querying through the new LINQ (Language Integrated Query).
With the help of the anonymous types we can define a type without declaring it from before hand. The main difference between the defined types and anonymous types is that we leave the type name in the anonymous types. The compiler will parse the syntax and create a standard CLR type itself for the definition of the type. Here is an example of an anonymous type.
var blog = new
{
PostId = 1,
Postname = "Anonymoust Type Post",
Category = 1
};
As you can see here I have defined an anonymous type here. The type was never defined before. While compiling the code the compiler itself will create a new type with three properties as defined above. The actual name for the type will be generated by the C sharp compiler so for CLR there is no difference between the Anonymous types and defined types.
The best thing about all these is that in the Visual Studio you will get full intelligence on the anonymous type along with the compile time checking. Check the image above to how the visual studio helps with the fields on the anonymous types.

I think the new anonymous types will be of great help specially when working with LINQ query and hierarchical data.
Thanks Vikram
|
Posted on 8/11/2007 8:55:21 AM
|
Posted on 8/14/2007 3:57:17 AM
What is the difference between the above anonymous type and structure datatype OR enum?
|
Posted on 8/14/2007 6:44:51 PM
HI contTech
For the new Anonymous type there was no type defined beforehand. The compiler created the class at the compile time itself. We do not have to declare the class.
|
Posted on 8/14/2007 9:26:20 PM
|