Mind the runtime optimization

You might know this already, but in C# when­ev­er you write some­thing like this:

   1: if (MethodA() || MethodB())

   2: {

   3:     // do something

   4: }

it’s not guar­an­teed that both meth­ods will be exe­cut­ed, so DO NOT DO THIS if you’re rely­ing on both meth­ods to be expect­ed to cause some desir­able side-effects.

The rea­son for this is sim­ple, at run­time, as soon as one of the meth­ods returns true the whole expres­sion will eval­u­ate to true regard­less of the out­put of the sec­ond method. So as far as the run­time is con­cerned, it can safe­ly skip the sec­ond part of the if con­di­tion as a form of run­time opti­miza­tion.

Here’s a quick demo that shows this behav­iour in action:

   1: public class MyClass

   2: {

   3:     public bool FlagA { get; set; }    

   4:     public bool FlagB { get; set; }

   5: }


   7: public bool MethodA(MyClass myObj)

   8: {

   9:     myObj.FlagA = true;    

  10:     Console.WriteLine("Set FlagA to true");


  12:     return true;

  13: }


  15: public bool MethodB(MyClass myObj)

  16: {

  17:     myObj.FlagB = true;    

  18:     Console.WriteLine("Set FlagB to true");


  20:     return true;

  21: }


  23: ...


  25: var myObj = new MyClass();


  27: // this evaluates to true, but only MethodA is invoked

  28: var isMyObjChanged = MethodA(myObj) || MethodB(myObj);


  30: // prints FlagA [True], FlagB[False]

  31: Console.WriteLine("FlagA [{0}], FlagB[{1}]", myObj.FlagA, myObj.FlagB);

This behav­iour also applies out­side to if state­ments like the one at the top of the post. I wast­ed some valu­able min­utes try­ing to solve a WTF bug result­ing from this, hope­ful­ly it won’t catch you out too!

Liked this post? Why not support me on Patreon and help me get rid of the ads!