On a regular basis (but not regular enough to remember all the subtleties involved), I need to explain to people why I think using the WITH statement in C/SIDE is potentially a bad idea. This blog post gives me something to refer them to, and to occasionally remind myself of my reasons. 😉

First of all, the WITH statement certainly has it’s applications. We all have a limited number of keystrokes we can type in our lifes, so any time you can avoid typing something should be considered a win. However, if saving keystrokes increases your chances of wasting even more precious time debugging, there’s an easy trade-off to be made.

In my own experience, WITH can cause really mind-boggling bugs in places that already have an explicit or implicit “scope variable”:

  • within another WITH statement (explicit; the outer WITH’s variable is your “scope variable”);
  • (sub)objects that have an implicit record variable, e.g. Rec in tables and pages, data item variables in reports etc.

The risk here is that the meaning of your code can change dramatically without any changes to the code itself if a named item is introduced in your WITH statement’s variable and something by that same name already was reachable outside of your WITH statement. Let me give an example.

Imagine we have a codeunit with the following code. Normally, of course, you would have more statements nested within your WITH statement; I left them out for simplicity’s sake.

Initial Codeunit

Running this gives us the following – unsurprising – result:

Initial result

However, if I now introduce a table function with the same name, the code in my codeunit gets a different meaning, without me even opening the codeunit. Perhaps somebody else made that change, and I don’t even have permissions to edit the codeunit. Or the table, for that matter.

A New Table Function

When I run my codeunit again, things will look like this:

Oops. An unexpected result.

In other words, WITH in situations with a “scope variable” is a time bomb: it may work flawlessly now, but there’s a risk it will blow up in your face in the future, without an obvious cause. That does not sound like the defensive code I normally try to write, which is why I tend to avoid WITH statements in general.