BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

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.

Examples:

[…] 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.

Examples:

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

Rate this Article

Adoption
Style

BT