VB.NET and the WITH statement

by Svelmoe 20. April 2009 20:23

I love using the WITH statement in VB.NET/ASP.NET because it eases up on the typing and helps “group together” functionality.
However, I found a fun little something when using the WITH statement, which I wanted to share.

It seems that you can assign a new object reference within a WITH statement to the specific object, however you can’t assign values to said new reference. Strange indeed, but I’m sure there’s some underlying reason.
Here some code to illustrate.

Suppose I have a class:

Private Class Test
        Private m_Text As String

        Public Property TextValue() As String
            Get
                Return m_Text
            End Get
            Set(ByVal value As String)
                m_Text = value
            End Set
        End Property
End Class

Then I have some code which uses this class in a WITH statement:

Dim obj As New Test()
obj.TextValue = "Test"
  For i As Integer = 0 To 10
   With obj
     If Not String.IsNullOrEmpty(.TextValue) Then
          System.Diagnostics.Debug.WriteLine("VALUE: " & .TextValue)
    Else
         System.Diagnostics.Debug.WriteLine("VALUE NOTHING")
    End If
    obj = New Test()
    .TextValue = "test" & i
   End With
Next

When run this provides the output:
VALUE: Test
VALUE NOTHING

And "nothing" for every subsequent run.
So it is possible to assign a new reference to the “obj” object reference, but the assignment of the new TextValue is ignored.

Not that usefull, but fun enough in my book :) (yes, I’m a geek

About Svelmoe

My real name is Allan Svelmøe Hansen.

I live in Denmark, where I work as a developer for hedal:kruse:brohus using SQL Server and the .NET framework since 2004. Svelmoe.dk is a place for my every day thoughts and reactions and the occasional technical blog entry.

I also blog about SQL and MS SQL Server at www.execsql.com so in case you are looking for more about that, please visit that website.



View Allan Svelmøe Hansen's profile on LinkedIn     

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010 Svelmoe.dk