Friday, April 4, 2008

Anonymous Types

Anonymous types (classes) allow you to create a class with members without actually defining a class first. You saw a small example of this under the var Variable post.

Before:
public class Person() 
{     
     // Auto Implemented Properties
     public string FirstName { get; set; }
     public string LastName { get; set; } 
} 

Person person = new Person(); 
person.FirstName = "Mark"; 
person.LastName = "Moeykens";
After:
var person = new {
                     FirstName="Mark", 
                     LastName="Moeykens"
                 }; 

// The FirstName member will appear in intellisense
string firstName = person.FirstName; 
Notice "FirstName" and "LastName" are being initialized within the braces. This is a new feature of C# 3.0 called Object Initializing. The variable 'person' will also have full intellisense.

More Info: MSDN: Anonymous Types