Short circuit expressions in VB.NET

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. 

Dom Finn

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment


Post a Comment