Nasuno
Nasuno

Reputation: 31

Stacking If Not's seems poor

You can stack these. Is there a better way?

If Not VAR_watchfolders_NewFile Is Nothing Then

If Not VAR_watchfolders_NewFile = VAR_HoldThisVAR Then

I need to hold back items from a list that gets deleted and prevent them from reoccurring in subsequent lists.

Upvotes: 1

Views: 48

Answers (3)

krivtom
krivtom

Reputation: 24916

In VB.NET there are 2 operators that you can use to combine multiple conditions:

And. If this operator is used, then both of your conditions will be evaluated. So if you use

If Not VAR_watchfolders_NewFile Is Nothing And Not VAR_watchfolders_NewFile = VAR_HoldThisVAR Then

then this will fail, because second condition will throw an exception.

AndAlso. If this operator is used, then right condition will only be evaluated if left condition is true. This means that if you can safely use code

If Not VAR_watchfolders_NewFile Is Nothing AndAlso Not VAR_watchfolders_NewFile = VAR_HoldThisVAR Then

and if left condition Is false right condition will never be evaluated. For C# users it is identical to using &&

Upvotes: 1

Heinzi
Heinzi

Reputation: 172438

You can use the short-circuiting AndAlso operator:

If VAR_watchfolders_NewFile IsNot Nothing _
    AndAlso VAR_watchfolders_NewFile <> VAR_HoldThisVAR Then

    ... 
End If

This ensures that the second condition is only evaluated if the first one evaluates to True. You can also replace Not ... Is Nothing with ... IsNot Nothing and Not ... = ... with ... <> ... to improve the readability of your code.

Upvotes: 2

avoliva
avoliva

Reputation: 3366

I believe you can just do this

If Not VAR_watchfolders_NewFile is Nothing And Not VAR_watchfolders_NewFile = VAR_HoldThisVAR Then

The second expression won't be evaulated if VAR_watchfolders_NewFile is Nothing, so you shouldn't have to worry.

Upvotes: 0

Related Questions