Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

New York City .NET

The author of the NYCdotNet blog is a VB.NET and SQL server developer living and working in New York City. The author seeks to promote clean, readable, efficient code in both VB and SQL from design to development, deployment, and application maintenance.

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.

Comments

Leave a comment on the original post [nycdotnet.blogspot.com, opens in a new window]

Loading comments...