Anonymous Types

Tuesday, 25 October 2011

Anonymous Types

Anonymous types is idea that might be familiar to you from dynamic languages.
Anonymous types are useful when you need a transient, fleeting type and you don’t want to do the work to create a class.

Here’s an example of creating an anonymous type in C#:
var customer = new {FirstName = “Stephen”, LastName = “Walther”};

Here’s how you would create the same anonymous type in VB.NET:
Dim customer = New With {.FirstName = “Stephen”, .LastName = “Walther”}
New C# and VB.NET Language Features

The customer variable is used without specifying a type, which looks very much like
JavaScript or VBScript. However, you need to understand that customer does have a type;
you just don’t know its name: It’s anonymous.

In a single line of code, we’ve managed to both create a new class and initialize its properties.
The terseness brings tears to my eyes.

Anonymous types are useful when working with LINQ to SQL because you’ll discover that
you often need to create new types on-the-fly. For example, you might want to return a
class that represents a limited set of database columns when performing a particular query.

No comments:

Post a comment