Tuesday, February 10, 2009

Introduction to LINQ - Part 2 - Anonymous types

Before jumping right into the LINQ asnd its implementation, I would like to introduce some new features of dot net framwork 3.0/3.5 that were incorporated to support LINQ.

In this article, we will discuss Anonymous types

First thing about Anonymous types is that it uses the keyword var. The var introduced with .NET 3.5 indicates an anonymous types. A developer who has worked in VB6, may say that var was there in VB6 also. So what's the difference?

Anonymous types defined with var are not similar to VB variant. So what is var?
The var keyword signals the compiler to emit a strong type based on the value of the operator on the right side.

A simple anonymous type begines with a var keyword, the assignment operator and a not null initial value.

var title="Tutorial on LINQ";

here the data type of var will be set based on the data type of the right hand side. So the datatype of title will be string.

As you will notice that I have mentioned that we need to assigna 'not null initial value'.

Anonymous types must always have an initial assignment and it can’t be nullbecause the type is inferred and fixed to the initializer.

Summary
Anonymous types are strong typeswhere the compiler does the work of figuring out the actual type and writing the classimplementation, if the anonymous type is a composite type.

No comments: