- Home /
How to put null & non-null value calculation in 1 if statement
Hi
Here is my current code:
if(_path != null)
{
if(_currentWaypoint >= _path.vectorPath.Count)
{
endMovement();
}
}
Ideally I wanted the code to read:
if(_path != null && _currentWaypoint >= _path.vectorPath.Count)
{
endMovement();
}
However because _path is sometimes null, get a null reference error when I try the above code.
Is there a way I achieve having both logic checks in 1 if statement?
Answer by robert_southee · Mar 07, 2015 at 07:11 PM
You may get a null reference exception if the _path.vectorPath is null.
if (_path != null && _path.vectorPath != null && _currentWaypoint >= _path.vectorPath.Count)
{
endMovement();
}
Answer by Glurth · Mar 07, 2015 at 07:16 PM
Not that I know of. You could avoid checking it, if you take care that it always exists (like I hope you do with the VectorPath list inside the _Path!)
But here is a syntax variant that you might like. It uses the ? operator: https://msdn.microsoft.com/en-us/library/ty67wk28.aspx
if( (_path!=null)? _currentWaypoint >= _path.vectorPath.Count : false )
{
Stuff();
}
Actually when using x&&y, if x is false then y will not be evaluated. https://msdn.microsoft.com/en-us/library/2a723cdk.aspx
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# if Statement Checking for Null Causing Null? 1 Answer
How to get around adding loads of "if" commands in my script 2 Answers
NullReferenceException 1 Answer