Pilispring
Pilispring

Reputation: 97

Nully the null error

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

Answers (6)

techfun
techfun

Reputation: 953

You can modify the if condition as follows:

if (ispunchactivated == true || (playermove!=null && playermove[i].name == "punch" ))

Upvotes: 3

Prasad Kanaparthi
Prasad Kanaparthi

Reputation: 6563

Try this,

if ((ispunchactivated == true) || (playermove[i] != null && playermove[i].name == "punch" ))
{
    Do the punch;
}

Upvotes: 3

Azodious
Azodious

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

Morten Jacobsen
Morten Jacobsen

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

Rawling
Rawling

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

Albin Sunnanbo
Albin Sunnanbo

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

Related Questions