The following code
Sub Foo(i As Int32?)
Select Case i
Case Nothing ' <-- warning here
' Do something
Case 0
' Do something else
Case Else
' Do something different
End Select
End Sub
yields the following warning:
Warning BC42037: This expression will always evaluate to Nothing (due to null propagation from the equals operator). To check if the value is null consider using 'Is Nothing'.
Case Is Nothing, however, yields a syntax error:
Error BC30239: Relational operator expected.
Is there a way to use Select Case with a nullable value type and a case clause for the Nothing case?
This is the workaround I currently use. I look forward to other solutions which are less repetitive in the case of multiple Case clauses:
Select Case True
Case i Is Nothing
' Do something
Case i = 0
' Do something else
Case Else
' Do something different
End Select
I prefer to see the Select wrapped in an If in this situation. It feels more readable and logical to me, since the lack of a value usually requires a different type of behavior than the presence of a value.
Sub Foo(i As Int32?)
If i.HasValue Then
Select Case i
Case 0
' Do something else
Case Else
' Do something different
End Select
Else
' Do something
End if
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With