We encountered unexpected behavior with a null conditional statement if the value of the variable is Nothing.
The behavior of the following code confuses us a little
Dim l As List(Of Object) = MethodThatReturnsNothingInSomeCases()
If Not l?.Any() Then
'do something
End If
The expected behavior is what Not l?.Any()
is true if it l
does not have a record or if l
- Nothing. But if l
Nothing, the result will be false.
This is the test code we used to view the actual behavior.
Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Module Module1
Public Sub Main()
If Nothing Then
Console.WriteLine("Nothing is truthy")
ELSE
Console.WriteLine("Nothing is falsy")
End If
If Not Nothing Then
Console.WriteLine("Not Nothing is truthy")
ELSE
Console.WriteLine("Not Nothing is falsy")
End If
Dim l As List(Of Object)
If l?.Any() Then
Console.WriteLine("Nothing?.Any() is truthy")
ELSE
Console.WriteLine("Nothing?.Any() is falsy")
End If
If Not l?.Any() Then
Console.WriteLine("Not Nothing?.Any() is truthy")
ELSE
Console.WriteLine("Not Nothing?.Any() is falsy")
End If
End Sub
End Module
Results:
- Nothing is false.
- Nothing believable
- Nothing? .Any () is false
- Something? .Any () is false
Why is the latter not evaluated as true?
C # prevents me from writing this type of validation at all ...
source
share