Mind the runtime optimization

You might know this already, but in C# whenever you write something like this:

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

   2: {

   3:     // do something

   4: }

it’s not guaranteed that both methods will be executed, so DO NOT DO THIS if you’re relying on both methods to be expected to cause some desirable side-effects.

The reason for this is simple, at runtime, as soon as one of the methods returns true the whole expression will evaluate to true regardless of the output of the second method. So as far as the runtime is concerned, it can safely skip the second part of the if condition as a form of runtime optimization.

Here’s a quick demo that shows this behaviour in action:

   1: public class MyClass

   2: {

   3:     public bool FlagA { get; set; }    

   4:     public bool FlagB { get; set; }

   5: }

   6:  

   7: public bool MethodA(MyClass myObj)

   8: {

   9:     myObj.FlagA = true;    

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

  11:     

  12:     return true;

  13: }

  14:  

  15: public bool MethodB(MyClass myObj)

  16: {

  17:     myObj.FlagB = true;    

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

  19:     

  20:     return true;

  21: }

  22:  

  23: ...

  24:  

  25: var myObj = new MyClass();

  26:  

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

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

  29:  

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

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

This behaviour also applies outside to if statements like the one at the top of the post. I wasted some valuable minutes trying to solve a WTF bug resulting from this, hopefully it won’t catch you out too!

Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my newsletter


Hi, I’m Yan. I’m an AWS Serverless Hero and the author of Production-Ready Serverless.

I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.


Check out my new course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. Including basic concepts, HTTP and event triggers, activities, callbacks, nested workflows, design patterns and best practices.

Get Your Copy