Visual Basic 9 for the Insane – A class with no name – Anonymous Types

Standard

image

Now we’re starting enter strange territory.  I give you a syntax that allows you to create classes “on the fly” :

Dim loClasslessSmurf = New With {.Name = "Brainy", .AnnoyingTrait = "Whiny Voice"}

This syntax creates a “temporary” class with the properties you specify.  This is known as an “anonymous type”.  (Or a type with no name)  This is the equivalent of:

Public NotInheritable Class XXXX
  Public Name As String
  Public AnnoyingTrait As String
End Class

These classes do not have methods on them.  They are intended as useful temporary data holders for inline processing.  They were created for the LINQ language feature to allow results to be returned without having to create result container classes.

Differences between Cousins

It appears that the behaviour between VB9 and CSharp3.0 differs when creating an anonymous types.  If you create one in CSharp, the properties are read-only.  If you create them in VB9 the properties are writeable.

Leave a comment