简体   繁体   中英

Multiple compares within IF statement in Visual Basic

In my visual basic .net app I want to do comparison like

If myObject IsNot Nothing And myObject.property <> 0 Then
...
EndIf

The problem is that I get null reference exception when myObject is nothing. So I have to nest IF statements:

If myObject IsNot Nothing Then
    If myObject.property <> 0 Then
    ...
    EndIf
EndIf

Is it possible to do this comparison without nesting IFs?

You have to use AndAlso (equivalent to && in C#). This is the logical operator performing the short-circuiting logical conjunction. And performs the logical operation without shortcircuit (equivalent to & in C#) and thus analyses both operands.

AndAlso is a shortcircuited 'And'. If the first part isn't evaluated to true then the second part won't be evaluated and hence won't error

http://msdn.microsoft.com/en-us/library/cb8x3kfz.aspx

you can try like this:

If Not IsNothing(myObject) AndAlso myObject.property <> 0 Then
    ...
EndIf

Maybe it work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM