Saturday, February 2, 2013

Using Inline “With” Blocks to Augment a VB.NET Default Constructor

Say you have a simple data transfer class that looks like this:

Public Class Employee
    Public Property Name As String
    Public Property HireDate As Date
    Public Property EmployeeID As Integer
End Class

Normally to load up this class, you might call something like this:

Dim employee As New Employee
employee.Name = "Steve"
employee.HireDate = #1/1/2013#
employee.EmployeeID = 12345

In this case there is an implied Public Sub New() that gets called for you when the class is instantiated.  However, you could also call this:

Dim employee As New Employee With {.Name = "Steve", .HireDate = #1/1/2013#, _
                                                       .EmployeeID = 12345}

Or in VB 2010 or higher which supports implied line continuation, this:

Dim employee As New Employee With {
                .Name = "Steve",
                .HireDate = #1/1/2013#,
                .EmployeeID = 12345,
            }

Note: if you happen to be inside a “With” block already, the inner “With” will take precedence over the scope of the outer “With”.  This applies to both inline “With” blocks and normal “With” blocks, though nesting “With” blocks is not recommended for code clarity’s sake.

No comments:

Post a Comment