Negating a null conditional statement returns nothing

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 ldoes not have a record or if l- Nothing. But if lNothing, 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 ...

+4
source share
1 answer

VB.NET Nothing ( SQL), #. , Boolean Boolean?, , True False, Nothing .

VB.NET , , , , .

, Nullable.HasValue:

Dim result as Boolean? = l?.Any()
If Not result.HasValue Then
    'do something
End If 

: VB.NET #?

+5

Source: https://habr.com/ru/post/1687624/


All Articles