1

I'm sorry if asked before...if so, I did not find it.

I was reading A Shortcut for c# null and Any() checks and I saw the accepted answer. I understand the answer, although most people use x.Items?.Any() ?? false.

My question is: How to do this is VB.NET

Could I just simply write

If x.Items?.Any() Then

or do I need

If x.Items?.Any() = True Then

While if (x.Items?.Any()) does not compile in C#, they both do in VB...but that doesn't always mean they are both correct :-)

diedie2
  • 366
  • 1
  • 6
  • 17

2 Answers2

1

When I tested the following on LinqPad:

Dim lst As List(Of Vehicle) = Nothing
If lst?.Any Then
    Console.WriteLine("True")
Else
    Console.WriteLine("False")
End If

it works just fine, and prints False, even with Option Strict On.

It also works from within Visual Studio in a .NET 5 console app.

It would seem that Visual Basic supports using Boolean? in the test of an If statement.

And it now seems to work on .NET Fiddle.

Zev Spitz
  • 13,950
  • 6
  • 64
  • 136
  • Your code will resolve to `False` because the `?` shortcut resolves to null/Nothing and the `Any()` is not even tested. If `lst` was not null but empty (ie `= New List(Of Vehicle)`), it would resolve to `False` due to the `Any()` test. – SteveCinq Mar 03 '21 at 16:26
  • @SteveCinq I'm not quite sure what you're trying to say. Isn't that the point? Whether the list is `Nothing`, or the list is empty, the "else" branch of the `If` will be executed. – Zev Spitz Mar 03 '21 at 16:30
  • Just highlighting the "why" side. Not a criticism. – SteveCinq Mar 03 '21 at 17:11
0

After doing some tests on .NET Fiddle I found out both work

Imports System
Imports System.Linq
            
Public Module Module1
  public Class Vehicle

  End Class

  Public Sub Main()

    Dim x as System.Collections.Generic.List(Of Vehicle)
    
    Dim y as System.Collections.Generic.List(Of Vehicle)
    y = new System.Collections.Generic.List(of Vehicle)
    
    Dim z as System.Collections.Generic.List(Of Vehicle)
    z = new System.Collections.Generic.List(of Vehicle)
    
    z.Add(new Vehicle())
        
    If (x?.Any() = True) Then
        Console.WriteLine("X YES")
    Else
        Console.WriteLine("X NO")
    End If
    
    If (x?.Any()) Then
        Console.WriteLine("X YES")
    Else
        Console.WriteLine("X NO")
    End If
    
    If (y?.Any() = True) Then
        Console.WriteLine("Y YES")
    Else
        Console.WriteLine("Y NO")
    End If
    
    If (y?.Any()) Then
        Console.WriteLine("Y YES")
    Else
        Console.WriteLine("Y NO")
    End If
    
    If (z?.Any() = True) Then
        Console.WriteLine("Z YES")
    Else
        Console.WriteLine("Z NO")
    End If
    
    If (z?.Any()) Then
        Console.WriteLine("Z YES")
    Else
        Console.WriteLine("Z NO")
    End If
End Sub
End Module

will result in

X NO
X NO
Y NO
Y NO
Z YES
Z YES

as excpected

diedie2
  • 366
  • 1
  • 6
  • 17