Anonymous Types

 Rate It (0)

It's now possible to create class definitions on the fly.  This is the concept of anonymous types, where the type is based on the signature of the class.  To create an anonymous type, use the following:

new { First = "B", Second="C" };

With this new type, we now have a new class with a First property of type string, and a Second property of type string.  However, nothing happens with the class because we have to store it somewhere.  This is where the "var" keyword comes into play:

var stringValue = "X";
var instance = new { First = "B", Second = stringValue };

Instance now represents our anonymous type. The compiler will parse the above syntax and create a standard CLR type which has 2 properties First and Second and assign these properties type based on the inilization values. Here both the property will have type string as they have been inilized as string.

 In Visual Studio 2008, there is full intellisense support for this.  When creating an anonymous type, make sure a value is supplied to the property, or that it can infer the type from a variable; otherwise, if a null is supplied, a compile error occurs.

Revision number 2, Friday, July 04, 2008 10:42:27 AM by vik20000in

Comments

Related Articles

New in Visual Studio 2008

Visual Studio 2008is theversion of Visual Studio which comes with the .NET Framework 3.5. It was released to MSDN subscribers on 19 November 2007 alongside the.NET Framework 3.5. Visual Studio 2008 can target developmentin .NET Framework versions 2.0, 3.0

Deployment

Deployment continues to get easier, but there's still a few gotchas here and there. Check out these choice articles for you deployment questions. Web Deployment Projects- Fritz Onion's most excellent article on Web Deployment Projects. He goes into

New "var" keyword

The var keyword is a new keyword that can infer its data type from the resulting set. For instance, look at the following examples: var one = 1; //infers an int var two = "2"; // infers a string var three = from c in Customers select c; //infers

LINQDataSource

There's quite a few data source controls in ASP.NET and one that folks are increasingly excited about is the LINQDataSource. Blogs LINQ to SQL (Part 5 - Binding UI using the ASP:LinqDataSource Control) - This is the best place to start to get your head around

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. tmorton (6)
  2. vik20000in (2)
  3. sambeetpatra (1)
  4. mbanavige (1)
  5. Jos Branders (1)
  6. anonymouswrites (1)

Advertise Here

Microsoft Communities
Page view counter