Nous avons rencontré un comportement inattendu avec l'opérateur conditionnel null si la valeur de la variable est Nothing.Négation de l'opérateur conditionnel nul renvoie des résultats inattendus pour rien
Le comportement du code ci-dessous nous garde un peu confus
Dim l As List(Of Object) = MethodThatReturnsNothingInSomeCases()
If Not l?.Any() Then
'do something
End If
Le comportement attendu est que Not l?.Any()
est truthy si l
n'a pas d'entrée ou si l
est rien. Mais si l
est Rien, le résultat est faux.
Ceci est le code de test que nous avons utilisé pour voir le comportement réel.
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
Résultats:?
- Rien est falsy
- rien est truthy
- Rien .Tout() est falsy
- rien est falsy .Tout()
Pourquoi n'est pas le dernier si l'évaluation à vrai?
C# me empêche d'écrire ce genre de contrôle tout à fait ...