Anyone have any ideas why this doesn’t work (C# or VB.NET or other .NET language doesn’t matter). This is a very simplified example of my problem (sorry for VB.NET):
Private itsCustomTextFormatter As String
Public Property CustomTextFormatter As String
Get
If itsCustomTextFormatter Is Nothing Then CustomTextFormatter = Nothing 'thinking this should go into the setter - strangely it does not'
Return itsCustomTextFormatter
End Get
Set(ByVal value As String)
If value Is Nothing Then
value = "Something"
End If
itsCustomTextFormatter = value
End Set
End Property
If you do:
Dim myObj as new MyClass
Console.WriteLine(myObj.CustomTextFormatter)
You will be surprised at the result. It will print “Nothing”. Anyone have any idea why it doesn’t print “Something”
Here’s a Unit Test per suggestion:
Imports NUnit.Framework
<TestFixture()> _
Public Class Test
Private itsCustomTextFormatter As String
Public Property CustomTextFormatter As String
Get
If itsCustomTextFormatter Is Nothing Then CustomTextFormatter = Nothing 'thinking this should go into the setter - strangely it does not'
Return itsCustomTextFormatter
End Get
Set(ByVal value As String)
If value Is Nothing Then
value = "Something"
End If
itsCustomTextFormatter = value
End Set
End Property
<Test()>
Public Sub Test2()
Assert.AreEqual("Something", CustomTextFormatter)
End Sub
End Class
This returns:
Test2 : Failed
Expected: "Something"
But was: null
at NUnit.Framework.Assert.That(Object actual, IResolveConstraint expression, String message, Object[] args)
at NUnit.Framework.Assert.AreEqual(Object expected, Object actual)
Your comment:
calls out what your error is. In Visual Basic there are two ways to return something from a function:
or
Mixing these two styles is perfectly legal, but confusing and a bad practice:
As you can see, you are mixing the two styles in the getter. Setting that variable does not call the setter; it informs the runtime that when the getter returns, this is the value that it should return. You then override that value with your
Returnstatement.If it hurts when you do that then don’t do that.