In C#, given the two methods
bool Action1(object Data);
bool Action2(object Data);
that are used in an if
statement like this:
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.
Action2() will only be called if Action1() returns false
This is conceptually similar to
if (Action1(Data))
{
PerformOtherAction();
}
else if (Action2(Data))
{
PerformOtherAction();
}
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;
}
}
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.
If Action1() returns true, Action2() will not be evaluated. C# (like C and C++) uses short-circuit evaluation. MSDN Link here verifies it.