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