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?
&&is a short circuiting operator, so the first way you wrote it and the second way will be functionally equivalent.bwill only be evaluated ifareturns true. (Same goes forc).In your code, checking
m.terms[0].labelswill not be a problem because you would have short-circuited out of the expression ifm.terms[0]had been null.To completely cover yourself, you’d want to possibly add checks for
mandm.terms, however.As it evaluates from left to right, it will break on the first condition that doesn’t pass and the rest will go unchecked.