You can short circuit expressions in VB.NET to help give your code some protection against the dreaded null reference exception, to save typing space and add to the readability of your code (in my opinion).
The full list of operators you can use to do this can be found on the MSDN site.
A great example is when you need to check a property of a reference type but need to check against it being null first. Ordinarily you would need a null check first and then inside the true branch of the null check, you can carry on with the logic.
If you see the code below for example:
The subject under test is the string extensions module, if line 9 did not include the AndAlso, and the variable "value" was null, the second part of the evaluation would create a null reference exception. With the AndAlso keyword, when the first part of the expression is evaluated as false, the whole expression returns false. The equivalent of AndAlso in C# is the && operator.
I hope that helps! I'm not sure I am going to continue down the path of showing unit tests for example I want to do as it's debatable how useful they are. In this example, if you copy the code into your Test Project, you can run the tests and watch them pass, however if you change the AndAlso to an And it the test class GivenANullString should fail.
I hope that helps! I'm not sure I am going to continue down the path of showing unit tests for example I want to do as it's debatable how useful they are. In this example, if you copy the code into your Test Project, you can run the tests and watch them pass, however if you change the AndAlso to an And it the test class GivenANullString should fail.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Imports System.Text | |
Imports Microsoft.VisualStudio.TestTools.UnitTesting | |
Imports System.Runtime.CompilerServices | |
Module StringExtensions | |
<Extension()> | |
Public Function IsLongerThan10Characters(ByVal value As String) As Boolean | |
Return value IsNot Nothing AndAlso value.Length > 10 | |
End Function | |
End Module | |
<TestClass()> | |
Public Class GivenANullString | |
Dim _result As Boolean | |
<TestInitialize()> | |
Public Sub Setup() | |
Dim value As String = Nothing | |
Me._result = value.IsLongerThan10Characters() | |
End Sub | |
<TestMethod()> | |
Public Sub AndAlsoShouldShortCircuit() | |
Assert.IsFalse(Me._result) | |
End Sub | |
End Class | |
<TestClass()> | |
Public Class GivenAString | |
Dim _result As Boolean | |
<TestInitialize()> | |
Public Sub Setup() | |
Dim value As String = "Good Day Sir" | |
Me._result = value.IsLongerThan10Characters() | |
End Sub | |
<TestMethod()> | |
Public Sub AndAlsoShouldShortCircuit() | |
Assert.IsTrue(Me._result) | |
End Sub | |
End Class | |
0 comments:
Post a Comment