Problem with Case Statement in Business Central 13

This is a a pretty niche post. Hopefully this problem only exists in a specific set of circumstances, in Business Central v13, but we wasted enough hours of our lives chasing it down yesterday that I thought I’d share it.

Consider this case statement:

i := 3;
test := true;

case i of
  1:
    exit('i equals 1');
  2:
    if test then
      exit('i equals 2, test is true')
    else
      if true then
        exit('you shouldn''t be here');
  else
    exit('i equals something else');
end;

exit('something bad has happened');

It exits with the result “i equals something else” – as you’d expect.

But if you replace the tests in the case with something more complex – one() and two() are methods that return integer 1 and 2:

i := 3;
test := true;

case i of
  one():
    exit('i equals 1');
  two():
    if test then
      exit('i equals 2, test is true')
    else
      if true then
        exit('you shouldn''t be here');
  else
    exit('i equals something else');
end;

exit('something bad has happened');

Now it exits with “something bad has happened”. The else of the case statement (line 10) is jumped over and the final exit line is hit instead.

It seems like the final else is attached to the previous if and no longer as part of the case statement. Putting begin…end around the previous case solves the problem.

i := 3;
test := true;

case i of
  one():
    exit('i equals 1');
  two():
    begin
      if test then
        exit('i equals 2, test is true')
      else
        if true then
          exit('you shouldn''t be here');
    end;
  else
    exit('i equals something else');
end;

exit('something bad has happened');

Putting a begin/end here is something I would have done previously anyway – to make the intention of the code clear – even though the code analyser now warns that they aren’t needed here.

As far as we can see this all works as expected in BC 14 and above, but is broken in all versions of BC 13.