VB Orcas anonymous syntax feels wrong
Posted
Wednesday, May 30, 2007 8:53 PM
by
bill
Earlier today I noticed a comment from Tim Ng on my early blog about mutable anonymous types. It was one of those comments that just felt wrong.... the more I thought about this the more I realised just how wrong it is.
To allow for mutable and immutable anonymous types, Paul Vick indicated VB will introduce a Key keyword to be used inside the With declaration,, e.g.
Dim customer As New With {Key .Id = 1, .Name = "Fred"}
Now theoretically this will give you a class with this signature:
Class Foo
Sub New(ByVal id As Int32)
Me.m_ID = id
End Sub
Private m_ID As Int32
Private m_Name As String
Public ReadOnly Property ID() As Int32
Get
Return m_ID
End Get
End Property
Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal value As String)
m_Name = value
End Set
End Property
End Class
I've omitted some of the details such as GetHashCode and Equals etc. Now if I was to try to write the same code with Foo instead of the anonymous type the code would fail.
Dim customer As New Foo With {Key .Id = 1, .Name = "Fred"}
Instead I have to use the only constructor and I can't set Id, and I can't set Id to be a key. The only valid syntax is:
Dim customer As New Foo(id) With { .Name = "Fred"}
So in reality we already have ways to work with readonly Properties that are only settable via a constructor. The With {} syntax also disallows setting ReadOnly properties, in fact in the above example intellisense will only display the Name property for Foo, which is all as it should be. But for some reason, one I have yet to fathom, the VB team has decided to allow you to set a ReadOnly property if you preference it with the new Key keyword.
Personally I think the syntax should be the same, be it anonymous types or existing types :
Dim customer As New Foo(id) With { .Name = "Fred"}
and
Dim customer As New(id) With { .Name = "Fred"}