Mutable and immutable anonymous types in VB

Bill McCarthy explained this to me in an email.

He wrote about it in this excellent article in Visual Studio Magazine "Drill Down on Anonymous Types".

But it still bit me in the ass!

So I am stamping this into my memory:

in a queryresults in
...select cust.CustomerID.cust.CompanyName...  Immutable anonymous type
...select New With {
                                .CustomerID=cust.CustomerID,
                                .CompanyName=cust.CompanyName} ...
Mutable anonymous type
...select New With {
                             Key .CustomerID=cust.CustomerID,
                             Key.CompanyName=cust.CompanyName} ...
Immutable anonymous type
Direct creation of object 
New With {
                 .CustomerID=cust.CustomerID,
                 .CompanyName=cust.CompanyName}
Mutable anonymous type
New With {
                  Key .CustomerID=cust.CustomerID,
                  Key .CompanyName=cust.CompanyName}
Immutable anonymous type

And just in case someone who really needs this stumbles on this post, two clarifications:

  1. All anonymous types are immutable in C#.
  2. Mutable means changeable, editable. Immutable means written in stone.

#1 Kathleen Dollard on 1.23.2008 at 9:15 PM

An extension of what you are saying...All properties of the anonymous type that are marked with "Key" are immutable. Other properties are no immutable.As you say, C# uses entirely immutable types. VB gives you the option of fully immutable types, fully mutable types and anonymous types in which some things can be changed and others are immutable. Flexibiity is good, if occasionally confusing.

#2 Julia Lerman on 1.23.2008 at 9:33 PM

I didn't want to say it quite that way only because then I have to further explain how the shortcut method in the first example is interpreted by VB as a shortcut for all Key'd properties. It's a mouthful and Bill explains it so nicely.I look forward to more from you on this one, Kathleen! :-)

#3 Bill McCarthy on 1.24.2008 at 12:02 AM

Thanks ! :)

Leave a Comment