Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Select Case with nullable values in VB.NET?

Tags:

vb.net

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?

like image 520
Heinzi Avatar asked Apr 10 '17 12:04

Heinzi


2 Answers

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
like image 157
Heinzi Avatar answered Nov 10 '22 00:11

Heinzi


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
like image 45
Bradley Uffner Avatar answered Nov 10 '22 00:11

Bradley Uffner