Visual Basic 9 for the Insane – Constructors for Free

Standard

image

There are some activities, such as searching for an attendant at a hardware store, watching television commercials, waiting for a TFS build server to come free or buying a bus ticket, bore me. 

Writing Constructors also bores me to tears.  I know it makes things easier for others that use your classes, but creating then just disrupts my “flow”.  In the world of mocking it’s a good idea to expose your dependencies via alternate constructors, which I do.  A new syntax may free me from this burden.

“Object Intializers” (This is an American product so in this case the “z” spelling) are another name for a feature I call “constructors for free”.

Take a boring class that represents a smurf like this:

Public Class Smurf

  Public AnnoyingTrait As String
  Public Name As String

End Class

If you want to create an instance of this class and want to set some defaults, the usual way of doing this is:

Dim loSmurf As New Smurf
loSmurf.AnnoyingTrait = "Whiny voice and Glasses"
loSmurf.Name = "Brainy"

Three lines of code!  The usual thing to do would be to create a constructor (Public Sub New), but this just moves the 3 lines of code elsewhere.  A far cooler thing to do is to use the new “Object Initializer” syntax:

Dim loSmurf As New Smurf With { .AnnoyingTrait = "Whiny voice", .Name="Brainy"}

Cool eh?  Additionally you can include these in array intializers so that you can create arrays with pre-intialized values:

Dim loSmurfs() = New Smurf() { _
     New Smurf With {.AnnoyingTrait = "Whiny voice", .Name = "Brainy"}, _
     New Smurf With {.AnnoyingTrait = "Unrealistic Beard", .Name = "Papa"}, _
     New Smurf With {.AnnoyingTrait = "Isn't a smurf", .Name = "Dopey"} _
     }

(Because of the “Implicit Types” feature you can also leave out the “New Smurf()” bit if you wanted to)

I pleased to report all this works fine in Compact Framework 2.0 (with VS2008).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s