I came across a language behavior today that I wasn’t expecting. Now I’m eager to learn why. Consider the following example:
try
{
worksheet.AddCell(row, cell++, image.DisplayCaption());
}
catch (NullReferenceException)
{
cell++;
throw;
}
In my example, image was null causing this line to throw a NullReferenceException; however, cell was still incremented and, of course, it was incremented again in the catch block. Why was the first post increment operation executed? In addition, would it have been executed if worksheet was null?
Thanks, Pete
Arguments of method call are evaluated from left to right.
Instead of catching
NullRefereneExceptionuseif(image != null). Exceptions are slow.Order of things happening:
cellis copied for the value parametercellis incremented as the last operation of the second parameter’s expression:cell++image.DisplayCaption()worksheet.AddCell(row, <non-incremented value>, <result of DisplayCaption()>);Since step 3. results in
NullReferenceExceptionstep 4. doesn’t happen.