This question applies to every programming language that has a short-circuit AND operator, not just C#.
The question is simple – is using short circuit evaluation to avoid an out of range index exception, for example:
if ((x > 0) && (bar[x] == foo))
or
if (((x > 0) && (x < bar.Length)) && (bar[x] == foo))
bad coding style? I know I could nest the loops like this:
if (x > 0)
{
if (bar[x] == foo)
{
}
}
but I find it to be extremely unreadable.
I would say that
is not bad coding style. It’s probably even good. I would definitely prefer it to a nested
ifstructure like you describe.As an aside, I would reduce the number of parentheses you use. Both these are equally correct, at least in C# and most other C-derived languages:
Readers who know the language (you have to assume this at some level) will easily be able to understand the above short-circuit expressions. Those readers would probably object to the nested
ifstyle, because it takes way more room than is necessary to get the correct behaviour.