0

I have simple loop:

For Each Pla As Player In Game.Players
    Dim JustForTest As String
    JustForTest = If(Pla.Name,  Continue For)
    Console.WriteLine(JustForTest)
Next

If the player's name is nothing, it should skip to the next item(or player), but I got this error at "Continue For":

BC30201 Expression expected.

Of course I can use like this:

For Each Pla As Player In Game.Players

    If Pla.Name = nothing then
    Continue For

    end if
    Console.WriteLine(Pla.Name)
Next

But I'm just curious what I was doing wrong, or is it a bug in VB?

2 Answers 2

2

The If Operator expects an Object to be passed into it as arguments, not a control statement. It is meant to be an equivalent to the ternary operator you'll find in other programming languages. You are trying to assign the value Continue For to your JustForTest variable -- and that just doesn't make sense.

It's not a bug in VB, just you trying to use the operator for something it's not designed to do.

5
  • The If operator as used in his example, is actually a null coalesence operattor, not a ternary. The ternary form has three arguments
    – jmoreno
    Oct 6, 2015 at 17:15
  • @jmoreno you are correct. I've always thought of it as a shortcut to If(x IsNot Nothing, x, y). Coalesce is a term we see often in Sql for example, but less so in other languages I use.
    – TZHX
    Oct 6, 2015 at 17:28
  • Null coalesence and nebcgodggeufcxje. Cntgpg mm ,umuo
    – jmoreno
    Oct 6, 2015 at 17:58
  • @jmoreno just that, yes.
    – TZHX
    Oct 6, 2015 at 17:59
  • Sorry, I started to comment using my iPad and was interrupted...I was going to say that null coalescence and propogation are valuable ideas, that are prominent in sql, but valuable in other languages as well. For instance the new ref?.property syntax for vb/c# is a welcomed addition of a null propogation operator.
    – jmoreno
    Oct 7, 2015 at 13:48
-1

The best way to compare to the Nothing (null in C#) is to use the Is or IsNot comparers, like: If obj Is Nothing Then. If your Name property is supposed to be a string then it is better if you use a String function like String.IsNullOrEmpty().

Your continue For looks correct according to the documentation.

https://msdn.microsoft.com/en-us/library/5z06z1kb.aspx#Anchor_4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.