Sunday, August 26, 2007 12:00 AM bart

Visual Basic 9.0 Feature Focus - Anonymous types

Welcome back to the Visual Basic 9.0 Feature Focus blog series. In this post, we'll cover Anonymous types, a feature also available in C# 3.0. The need for anonymous types originates from projection clauses in LINQ statements which typically cook up a new ad-hoc type containing the data of interest. Nevertheless, anonymous types are useful in isolation too, for instance to group a couple of variables together without having to build a special type for that sole purpose.

Anonymous type syntax is similar to Object Initializer syntax (see previous post in my Visual Basic 9.0 Feature Focus series) and looks like this:

Dim t = New With {.Name = "Bart", .Age = 24}

The part between the curly braces can contain an arbitrary number of initializers which follow the syntax conventions of With (i.e. starting with a dot). Notice this is a place where Implicitly Typed Local Variables are required in order to declare a variable of the anonymous type (which has some compiler-generated unspeakable name like VB$AnonymousType_0`2).

image

Notice the type overrides ToString which produces a comma separated key/value pair string between curly braces, like "{ Name = Bart, Age = 24}". The compiler is also smart enough to infer the name of the to-be-generated property if you're referring to another already-existing property, like this:

Dim t = New With {.Name = "Bart", .Age = 24}
Dim id = 123
Dim u = New With {.Id = id, t.Name, t.Age}

where the latest statement is equivalent to:

Dim u = New With {.Id = id, .Name = t.Name, .Age = t.Age}

One thing unique to VB 9.0 is the existence of so-called keyed anonymous types. In the previous samples, the Equals method will only return true if you're comparing two identical references with one another. Therefore, the following will print False:

Dim t = New With {.Name = "Bart", .Age = 24}
Dim u = New With {.Name = "Bart", .Age = 24}
Console.WriteLine(t.Equals(u))

even though both anonymous types denote the same "shape" and have the same values assigned. If you define one or more properties as a key using the Key keyword (that's a lot of keys in this sentence), these are used for the equality check (Equals) and the creation of a hash code (GetHashCode). Here's a sample that will print True:

Dim t = New With {Key .Id = 1, .Name = "Bart", .Age = 24}
Dim u = New With {Key .Id = 1, .Name = "Anders", .Age = 47}
Console.WriteLine(t.Equals(u))

Both objects are the same because (all) the keys are equal: only the fields marked with Key are compared to do the equality test. Geeks can check this easily using ILDASM.

We'll encounter anonymous types again when talking about LINQ query syntax later in this series. A little sample of a projection inside a VB 9.0 LINQ query is shown below:

Dim res = From c In customers Select New With {c.Name, c.Age}

Happy coding!

Del.icio.us | Digg It | Technorati | Blinklist | Furl | reddit | DotNetKicks

Comments

# University Update-T-Pain-Visual Basic 9.0 Feature Focus - Anonymous types

Pingback from  University Update-T-Pain-Visual Basic 9.0 Feature Focus - Anonymous types

# re: Visual Basic 9.0 Feature Focus - Anonymous types

Monday, August 27, 2007 1:16 AM by Corrado Cavalli

Where did you see the overload that returns the key=value pairs?

# re: Visual Basic 9.0 Feature Focus - Anonymous types

Monday, August 27, 2007 3:42 AM by bart

Hi Corrado,

Oops, little mistake; I meant overriding. The created anonymous type overrides the System.Object::ToString method. I've fixed this typo right now.

Thanks for the feedback,

-Bart

# 15 Links Today (2007-08-27)

Monday, August 27, 2007 8:20 AM by 15 Links Today (2007-08-27)

Pingback from  15 Links Today (2007-08-27)

# re: Visual Basic 9.0 Feature Focus - Anonymous types

Tuesday, August 28, 2007 1:22 AM by Corrado Cavalli

Hi Bart,

Please note that there is no ToString() override, what you see is a "weird" VB behavior and it should read: ToString()(index) that returns the string character at index position.  

# re: Visual Basic 9.0 Feature Focus - Anonymous types

Tuesday, August 28, 2007 8:12 AM by bart

Hi Corrado,

Just try the following in Orcas Beta 2:

Module Anon

  Sub Main()

     Dim a = New With { .Name = "Bart", .Age = 24 }

     Console.WriteLine(a.ToString())

  End Sub

End Module

You can omit the ToString() call if you want to do so. It will print:

{ Name = Bart, Age = 24 }

just as the equivalent code in C# 3.0 will do.

-Bart

# re: Visual Basic 9.0 Feature Focus - Anonymous types

Wednesday, August 29, 2007 1:42 PM by Corrado Cavalli

Hi Bart, You're right, my fault. Sorry...

# MSDN Blog Postings » New Features of Visual Basic 9 Article Series

Pingback from  MSDN Blog Postings  » New Features of Visual Basic 9 Article Series

# New Features of Visual Basic 9 Article Series

Thursday, September 27, 2007 5:47 AM by Walter Stiers - Academic Relations Team (BeLux)

In a series of 15 posts, Bart De Smet explores several of the new features in Visual Basic 9 . These

# Anonymous Types in C# 3.0 AND VB9

Thursday, January 31, 2008 5:46 AM by Letteer Lines

Anonymous Types in C# 3.0 AND VB9

# Recap of European Launch Events for Visual Studio 2008 (Amanda Silver)

Monday, March 24, 2008 4:44 PM by The Visual Basic Team

Last week I had the privilege of speaking in Lisbon, Portugal & Birmingham, England at launch events

# ヨーロッパでの Visual Studio 2008 発表イベントの要約 (Amanda Silver)

Monday, June 09, 2008 11:42 PM by The Visual Basic Team

先週、 ポルトガルのリスボン と イギリスのバーミンガム での Visual Studio 2008 の発表イベントで講演する機会がありました。どちらも熱狂的な雰囲気に包まれていたのは、今回の Visual

# VB 9.0 Feature Focus – Link Collection

Saturday, August 09, 2008 7:16 AM by B# .NET Blog

Collecting a few of my posts for easy quick reference: Visual Basic 9.0 Feature Focus – Introduction