Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 776
mjk6026 Avatar asked Jul 28 '11 15:07

mjk6026


3 Answers

&& 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.

like image 92
Anthony Pegram Avatar answered Oct 15 '22 12:10

Anthony Pegram


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; 
        }
    }
}
like image 32
Jalal Said Avatar answered Oct 15 '22 13:10

Jalal Said


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

like image 36
Bas Avatar answered Oct 15 '22 12:10

Bas