InfoQ Homepage News Another Look at Anonymous Types in VB

Another Look at Anonymous Types in VB


Anonymous types in C# are a rather simple affair, as they are always immutable. VB allows both mutable and immutable anonymous types, with subtly different rules for each.

Immutable Anonymous Types

Immutable anonymous types in C# and VB work the same way. Each is a collection of read-only properties with the Equals, ToString, and GetHashCode functions overridden. A look at the decompiled code shows that they are implemented in a slightly different fashion, but the end results are the same. In both cases, Equals and GetHashCode are based on all of the fields in the class.

In C# you always get immutable anonymous types. In VB, you only get them if you are using the Select clause in a query or you prepend the keyword "Key" to each field. For example:

var a = new { Name = "Tom", Age = 25 };
[…] Select c.Name, c.Age
[…] Select New With {Key c.Name, Key c.Age}
Dim a = New With {Key .Name = "Tom", Key .Age = 25}

Mutable Anonymous Types

Mutable types in VB are much simpler than their immutable counterparts. They do not have Equals or GetHashCode functions, so any kind of equality checks will have to be performed manually. It does however emit setters for all of the fields.


[…] Select New With { c.Name, c.Age}
Dim b = New With { .Name = "Tom", .Age = 25}

Partially Mutable Anonymous Types

Partially mutable types in VB are created by marking some, but not all, fields as Key. Key fields are exposed as read-only properties while non-key fields are read-write.

When it comes to the Equals and GetHashCode functions, some care must be taken. Only key fields are used by these functions, editable fields are ignored. This allows them to be safely placed in hash tables, an important consideration when query performance is crucial.


[…] Select New With {Key c.Name, c.Age}
Dim c = New With {Key .Name = "Tom", .Age = 25}

Rate this Article


Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Community comments

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p


Is your profile up-to-date? Please take a moment to review and update.

Note: If updating/changing your email, a validation request will be sent

Company name:
Company role:
Company size:
You will be sent an email to validate the new email address. This pop-up will close itself in a few moments.