mjk6026
mjk6026

Reputation: 1484

more short code about if statement

i wanted to try the following code:

//all arrays are List<T> type.
if (m.terms[0] != null && m.terms[0].labels != null && m.terms[0].labels[0].title == "Part-of-speech")
{
    result = true; 
}

but it occured runtime error occasionly in following situation

i. m.terms == null

ii. m.terms != null, but m.terms[0] does not intialized.

iii. m.terms != null, and m.terms[0] has been exist but m.terms[0].label does not initialized.

...

so i did modify it to like this:

if (m.terms[0] != null)
{
    if (m.terms[0].labels != null)
    {
        if (m.terms[0].labels[0].title == "Part-of-speech") { result = true; }
    }
}

is it the best way?

Upvotes: 5

Views: 472

Answers (5)

Anthony Pegram
Anthony Pegram

Reputation: 126804

&& is a short circuiting operator, so the first way you wrote it and the second way will be functionally equivalent.

if (a && b && c)
{
    // work 
}

b will only be evaluated if a returns true. (Same goes for c).

In your code, checking m.terms[0].labels will not be a problem because you would have short-circuited out of the expression if m.terms[0] had been null.

To completely cover yourself, you'd want to possibly add checks for m and m.terms, however.

m != null && m.terms != null && m.terms.Count > 0 && m.terms[0] != null ...

As it evaluates from left to right, it will break on the first condition that doesn't pass and the rest will go unchecked.

Upvotes: 7

Jalal Said
Jalal Said

Reputation: 16162

int index = 0;
int labelIndex = 0;
string titleToCheck = "Part-of-speech";

if (m != null && m.terms != null && m.terms.Count > index)// or m.Length...
{
    if (m.terms[index] != null && m.terms[index].labels != null &&
        m.terms[index].labels.Count > labelIndex)
    {
        if (m.terms[index].labels[labelIndex].title == titleToCheck)
        {
            result = true; 
        }
    }
}

Upvotes: 3

Arjun Shetty
Arjun Shetty

Reputation: 1585

try this

if (m!=null && m.terms!= null && m.terms[0].labels!=null && m.terms[0].labels[0].title!=null && m.terms[0].labels[0].title == "Part-of-speech")

Upvotes: 0

KennyRules
KennyRules

Reputation: 221

Yes, it would be better to split off each null check into a separate if statement.

The reason is that the second and third conditions require the first to not be null. If the first is null, then the second and third conditions will in turn throw errors because their parent is null yet is trying to be accessed.

Upvotes: -2

Bas
Bas

Reputation: 27085

This is all about readability. C# uses Short-circuit evaluation so in functionality there is no difference.

Upvotes: 1

Related Questions