Will all methods in a logical expressions be executed?

前端 未结 5 1950
我在风中等你
我在风中等你 2021-01-27 17:35

In C#, given the two methods

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

that are used in an if statement like this:

相关标签:
5条回答
  • 2021-01-27 17:57

    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.

    0 讨论(0)
  • 2021-01-27 18:02

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

    This is conceptually similar to

    if (Action1(Data))
    {
        PerformOtherAction();
    } 
    else if (Action2(Data))
    {
        PerformOtherAction();
    } 
    
    0 讨论(0)
  • 2021-01-27 18:16

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-27 18:16

    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.

    0 讨论(0)
  • 2021-01-27 18:22

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

    0 讨论(0)
提交回复
热议问题