C# 3.0, VB 9.0 and Anonymous Types

Rick Strahl talks about new C# 3.0 features, but leaves a few questions…


Why can’t you change the property values instances of anonymous types?


The problem is that instance of anonymous types are hashed by hashing all values. Thus, if values could change, all hashes would have to be updated (impossible with the .NET design) or hashes would not match and all sort of unacceptable side-effects like dictionaries no longer finding their key values.


Visual Basic used a different approach allowing you to identify individual properties as keys with the “Key” keyword. Only these values are readonly, while other properties can be changed.


Why can’t we pass around instance of anonymous types around?


We can! That was my Thanksgiving present this morning. Check this out… from Alex James


You do however need to know the structure in the receiving routine, and you’ll also needs some casts so this isn’t going to be quite as fast as a real class. I wanted to test this approach in VB console project:


Module Module1

      Sub Main() 

            Dim x = New With {.FirstName = “Fred”, .LastName = “Smith”}


            Test(x)

            Console.Read()       End Sub   

 


      Private Sub Test(Of T)(ByVal x As T) 

            Dim y = x.CastByType(New With {.FirstName = “”, .LastName = “”})             Console.WriteLine(y.firstName & “, “ & y.LastName)       End Sub   

 


      <System.Runtime.CompilerServices.Extension()> _ 

      Private Function CastByType(Of T)(ByVal x As Object, ByVal y As T)          Return CType(x, T)  

      End Function

End Module 

 


The trick is that the cast method takes another anonymous type declaration which matches the one we’re working with. The extension method makes the call look more natural, but I don’t think I’d use it in a real project because CastByType now shows up in Intellisense for every type – anonymous or not.


There’s been some confusion about signatures of anonymous types. These signatures include both name and type, which you can see if you change Test above:


   Private Sub Test(Of T)(ByVal x As T) 

      Dim y = x.CastByType(New With {.FirstName2 = “”, .LastName2 = “”})       Console.WriteLine(y.firstName2 & “, “ & y.LastName2)    End Sub  

 


This results in a runtime error on the cast in the CastByType methods. That’s one more reason to be careful where you use this technique.


Still it’s cool to uncover new things in .NET 3.5.


 


 

One thought on “C# 3.0, VB 9.0 and Anonymous Types”

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>