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.

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

4 thoughts on “Mutable and immutable anonymous types in VB

  1. 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. 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. I still can not edit cells in my dataGridView and below is my query, what am i doing wrong?

    Function LoadEmpRedundancy() As Object

    Using context As New MyEntity

    Dim myBooks = From b In context.Books _

    Select New With { _

    b.BookID, _

    b.BookDate, _

    b.BookName, _

    b.Col1, _

    b.Col2, _

    b.Col3, _

    b.Col14, _

    b.OtherCols}

    dataGridView1.AutoGenerateColumns = False

    dataGridView1.DataSource = Redundancy

    Return myBooks

    End Using

    End Function

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.