1

I have 2 separate functions, each one returns its own string value.

I am wanting to check that both return a specific string value and if they do then perform a task.

Example:

If function Apples returns "Apples" and Function Pears () returns "Pears" then do something

I am currently using 2 nested If statements and I want to know if this is the best way to do it.

If Apples() = "Apples" Then

        If Pears() = "Pears" Then
            "Do something here"
        End If

    End If
Ian Barber
  • 133
  • 8

1 Answers1

1

Using ANDALSO, if the first comparison fails, the second comparison is not made:

If String.Compare(Apples(),"Apples", True) = 0  ANDALSO  String.Compare(Pears(),"Pears", True) = 0 Then

    'Do Something Here

    End If

Be careful with string comparisons, the comparison is case sensitive. "Apples" <> "APPLES".

Another version:

If Apples().ToUpper = "APPLES" ANDALSO  Pears().ToUpper = "PEARS" Then
    
        'Do Something Here
    
        End If
Pete -S-
  • 542
  • 5
  • 13
  • 1
    Why are you making this more complicated than it has to be (using `String.Compare()`)? What's wrong with checking if `Apples() = "Apples"`? – 41686d6564 stands w. Palestine Jul 24 '20 at 22:12
  • @ Ahmed Abdelhameed: Case sensitivity. The other way would be to wrap UPPER or lower to prevent case sensitive comparison. – Pete -S- Jul 24 '20 at 22:14
  • 3
    Oh, I didn't notice you passed `True` for the `ignoreCase` parameter. Okay, fair point. I still wouldn't use `.Compare` if I wanted the comparison to be case-insensitive. `Applies().Equals("Apples", StringComparison.OrdinalIgnoreCase)` is better, IMO. – 41686d6564 stands w. Palestine Jul 24 '20 at 22:19
  • @ Ahmed Abdelhameed: Not know what the functions are supposed to do, instead of returning a string, have the function return a boolean. Then it becomes really easy to compare. If Apples() andalso Pears() Then – Pete -S- Jul 24 '20 at 22:21
  • @ Ahmed Abdelhameed: we have a lot of options for string comparison. One issue is, if a NULL/Nothing returned, handling that correctly. – Pete -S- Jul 24 '20 at 22:23