C# in Depth

Cover of C# in Depth
Order now (3rd edition)

Anonymous types in VB, and immutability

Chapter 8: Cutting fluff with a smart compiler: 8.5.2

Created: 3/15/2008
Last updated: 3/15/2008

As I point out in the book, anonymous types in C# are always immutable. I only recently learned that in VB, anonymous types can be wholly or partially mutable.

That doesn't sound too bad - choice is good, right? But anonymous types are mutable by default in VB. They're only immutable for properties decorated with Key. Ouch.

While it's obviously good that different languages can choose different paths, it seems odd to me that by default VB has chosen against immutability, while the rest of the world is trying to embrace it for its threading goodness (and other benefits, of course). I'm happy with C#'s choice to make anonymous types immutable, and I'd hope that if the C# team had decided to allow mutability, they'd have made that an explicit choice, with immutability the safer default.

It's really important that VB developers understand this, by the way - various LINQ operators such as Distinct rely on equality and hashing, which are only applied to immutable properties for anonymous types... if you're going to use those operators in VB, you must remember the Key modifier.