Reputation: 3415
I deal with this type of issue all the time and was wondering if you had any slick elegant work arounds:
if(myObject != null && myObject.myProperty != myValue){
//do something
}else{
//do something else
}
If I run this logic, I get null reference when myObject is null so I end up doing:
if(myObject != null){
if(myObject.myProperty != myValue){
//do something
}else{
//do something else
}
}else{
//do something else
}
So I end up having redundant code on my "do something else" how do you guys handle this?
Upvotes: 0
Views: 250
Reputation: 31184
your first statement is perfectly valid.
if(myObject != null && myObject.MyProperty != myValue)
What this will do is it will evaluate myObject != null
first, and since there's a &&
to the right of it, If it's false, it doesn't even need to evaluate the other clause.
If you just copy and paste the code you pasted here, I think you'll find that it runs successfully
Upvotes: -2
Reputation: 45083
The first check for null
means that the second condition won't be evaluated if that isn't met - when using logical AND (&&
) - so I suggest your null reference exception comes from elsewhere, not that latter condition.
Upvotes: 2
Reputation: 726489
There is no "elegant" way to deal with this - two ways of sharing the code of "do something else" are really of varying degree of non-elegance:
if
to say if additional processing is needed, and act on the flag upon exit from the if
statement.The first solution is self-explanatory; the second solution looks like this:
var processed = false;
if(myObject != null) {
if(myObject.myProperty != myValue){
//do something
processed = true;
}
// do more stuff knowing that myObject is not null
}
if (!processed) {
// do something else
}
Upvotes: 2