Reputation: 97
Is there a way to tell the program that i don't care if a class reference is null. For example:
if (playermove[i].name == "punch" || ispunchactivated == true)
{
Do the punch;
}
Why is he searching for the playermove (that can be null) and give me a null exeption error? i really don't care if the ispunchactivated is true.
Thanks.
Upvotes: 0
Views: 179
Reputation: 953
You can modify the if condition as follows:
if (ispunchactivated == true || (playermove!=null && playermove[i].name == "punch" ))
Upvotes: 3
Reputation: 6563
Try this,
if ((ispunchactivated == true) || (playermove[i] != null && playermove[i].name == "punch" ))
{
Do the punch;
}
Upvotes: 3
Reputation: 13882
Change your condition as follows:
if(playermove !=null && playermove[i] != null)
{
if (playermove[i].name == "punch" || ispunchactivated == true)
{
Do the punch;
}
}
Upvotes: 1
Reputation: 986
Just interchange the conditions and shortcircuitting will do that for you:
if (ispunchactivated == true || playermove[i].name == "punch")
{
Do the punch;
}
playermove[i]
is only evaluated if ispunchactivated
is false. That being said, you can still run into a null pointer exception if ispunchactivated
is false and playermove[i]
is null.
Upvotes: 2
Reputation: 50154
If you put your two conditions the other way around:
ispunchactivated /*== true*/ || playermove[i].name == "punch"
// this isn't necessary
then, if the first one is true, the second one won't be checked.
However, unless you know playermove[i]
won't be null if ispunchactivated
is false, you should really be making the null check too, otherwise you'll still get exceptions:
ispunchactivated ||
(playermove[i] != null && playermove[i].name == "punch")
Upvotes: 9
Reputation: 47058
You just check it for null first.
There are not shortcuts here.
if (playermove == null || playermove[i].name == "punch" || ispunchactivated == true)
{
Do the punch;
}
Upvotes: 4