Demonstrate the short-circuit operators : Operators « Language Basics « C# / C Sharp

Demonstrate the short-circuit operators /*
C#: The Complete Reference
by Herbert Schildt

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Demonstrate the short-circuit operators.

using System;

public class SCops {
public static void Main() {
int n, d;

n = 10;
d = 2;
if(d != 0 && (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);

d = 0; // now, set d to zero

// Since d is zero, the second operand is not evaluated.
if(d != 0 && (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);

/* Now, try the same thing without short-circuit operator.
This will cause a divide-by-zero error.  */
if(d != 0 & (n % d) == 0)
Console.WriteLine(d + " is a factor of " + n);
}
}

Related examples in the same category

 1 The + Operator Is Left Associative 2 Math Operators with int value 3 Demonstrate the difference between prefix postfix forms of ++ 4 Demonstrate the relational and logical operators 5 Side-effects can be important 6 Prevent a division by zero using the ? 1 7 Self increment 8 Self decrease 9 Illustrates the use of the comparison operators 10 Illustrates the use of the Boolean logical operators 11 Ternary operator 12 Illustrates the use of the ternary operator 13 Illustrates the use of the arithmetic operators 14 Illustrates the use of the bitwise operators 15 Illustrates the use of the shortcut operators 16 Prefix and postfix versions of the increment and decrement operators 17 Operator precedence 18 Demonstrates compound assignment operators 19 Relational Operators 3 20 Numeric Operators 3 21 Numeric Operators 1 22 Relational Operators 23 control the operator evaluation sequence 24 'logical and' and bitwise and 25 logical or and bitwise or 26 And Assignment 27 Or Assignment 28 Iff operator in C# 29 logical exclusive-or 30 Conditional operator and Math calculation 31 Add Assigment for both number and string value