public static void Or() { // Example #1 uses Method1 and Method2 to demonstrate // short-circuit evaluation. Console.WriteLine("Regular OR:"); // The | operator evaluates both operands, even though after // Method1 returns true, you know that the OR expression is // true. Console.WriteLine("Result is {0}.\n", ConditionalOr.Method1() | ConditionalOr.Method2()); /*Output: * Regular OR: * Method1 called. * Method2 called. * Result is True.*/ Console.WriteLine("Short-circuit OR:"); // Method2 is not called, because Method1 returns true. Console.WriteLine("Result is {0}.\n", ConditionalOr.Method1() || ConditionalOr.Method2()); /*Output: * Regular OR: * Short-circuit OR: * Method1 called. * Result is True.*/ // In Example #2, method Divisible returns True if the // first argument is evenly divisible by the second, and False // otherwise. Using the | operator instead of the || operator // causes a divide-by-zero exception. // The following line displays True, because 42 is evenly // divisible by 7. Console.WriteLine("Divisible returns {0}.", ConditionalOr.Divisible(42, 7)); /*Output: * Divisible returns True.*/ // The following line displays False, because 42 is not evenly // divisible by 5. Console.WriteLine("Divisible returns {0}.", ConditionalOr.Divisible(42, 5)); /*Output: * Divisible returns False.*/ // The following line displays False when method Divisible // uses ||, because you cannot divide by 0. // If method Divisible uses | instead of ||, this line // causes an exception. Console.WriteLine("Divisible returns {0}.", ConditionalOr.Divisible(42, 0)); /*Output: * Divisible returns False.*/ if (ConditionalOr.Method2() || ConditionalOr.Method1()) { Console.WriteLine("OR: if (false; true), both func exec cond => true"); } /* Output: * Method2 called. * Method1 called. * OR: if (false; true), both func exec */ if (ConditionalOr.Method1() || ConditionalOr.Method2()) { Console.WriteLine("OR: if (false; true), first func exec cond => true"); } /* Output: * Method1 called. * OR: if (true; false), fist func exec */ if (ConditionalOr.Method2() && ConditionalOr.Method1()) { Console.WriteLine("AND: if (false; true), first func exec cond => false"); } /* Output: * Method2 called. */ if (ConditionalOr.Method1() && ConditionalOr.Method2()) { Console.WriteLine("AND: if (true; false), both func exec cond => true"); } /* Output: * Method1 called. * Method2 called. */ }
void ConditionalOrIsInheritingAndRequireTrueFalseOperators() { var a = new ConditionalOr(); var b = a || a; }