Monday, December 10, 2007

Another nice shortcut in .NET 2.0

OK, who can tell me what's wrong with the following VB.NET code?

Public Sub MyMethod(ByVal inputString As String)

Try

' Validate input
If inputString Is Nothing Or inputString.Trim.Length = 0 Then
' However you want to handle the error...
End If

' More functionality here

Catch
' Error-handling code

End Try

End Sub

[Jeopardy theme plays...]

Basically, the line where we check the "nothing-ness" or "blank-ness" of inputString will always error-out if the string actually is nothing. This is because And and Or in VB.NET are not short-circuited. Both sides of the operator always run, and Nothing.Trim.Length will cause an invalid object exception. Technically, it's not worth checking the right side of an And if the left is false nor the right side of an Or if the left is true, but VB.NET does it anyways by default. If one argument in an And statement is false, the whole statement is false. If one argument in an Or statement is true, the whole statement is true (not counting exclusive or). To achieve this level of functionality, an earlier version of VB.NET introduced the AndAlso and OrElse operators. Basically, they will stop evaluating if the outcome can be determined after looking at just the left side of the statement. So, our code above would become:

If inputString Is Nothing OrElse inputString.Trim.Length = 0 Then

Now, with VB.NET 2.0, we have a new operator that achieves the same code as above. So, it can be further reduced to:

If String.IsNullOrEmpty(inputString) Then

Microsoft must have realized that people were having issues because they may have been used to languages where And and Or are short-circuited by default. It's a nice shortcut if you can remember to use it!

No comments: