views:

74

answers:

5

In C#, given the two methods

 bool Action1(object Data);
bool Action2(object Data);

that are used in an if statement like this:

if ( Action1(Data) || (Action2(Data) )
{
    PerformOtherAction();
}

will Action2() still be called if Action1() returned true, or is this prevented by compiler optimisation, since it is already known that the expression will evaluate to true?

+5  A: 

Action2() will only be called if Action1() returns false

This is conceptually similar to

if (Action1(Data))
{
    PerformOtherAction();
} 
else if (Action2(Data))
{
    PerformOtherAction();
}
Patrick McDonald
+5  A: 

No, C# support logical short-circuiting so if Action1 returned true it would never evaluate Action2.

This simple example shows how C# handles logical short-circuiting:

using System;

class Program
{
    static void Main()
    {
     if (True() || False()) { }  // outputs just "true"
     if (False() || True()) { }  // outputs "false" and "true"
     if (False() && True()) { }  // outputs just "false"
     if (True() && False()) { }  // outputs "true" and "false"
    }

    static bool True()
    {
     Console.WriteLine("true");
     return true;
    }

    static bool False()
    {
     Console.WriteLine("false");
     return false;
    }
}
Andrew Hare
+1  A: 

Action2 will not be called if Action1 returns true, due to the rules of short-circuit evaluation. Note that this is a runtime optimization, not a compile-time optimization.

+1  A: 

If Action1() returns true, Action2() will not be evaluated. C# (like C and C++) uses short-circuit evaluation. MSDN Link here verifies it.

Harper Shelby
+2  A: 

You can use a single | or & to get both methods to execute. It's one of the tricks that the Brainbench C# exam expects you to know. Probably of no use whatsoever in the real world but still, nice to know. Plus, it lets you confuse your colleagues in creative and devious ways.

Dmitri Nesteruk
Thanks! Can you provide a link to a document that explains this further, please?
Treb