The ? Operator


One of C#’s most fascinating operators is the ?. The ? operator is often used to replace certain types of if-then-else constructions. The ? is called a ternary operator because it requires three operands. It takes the general form

 Exp1 ? Exp2: Exp3; 

where Exp1 is a bool expression, and Exp2 and Exp3 are expressions. The type of Exp2 and Exp3 must be the same. Notice the use and placement of the colon.

The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated, and its value becomes the value of the expression. Consider this example, which assigns absval the absolute value of val:

 absval = val < 0 ? -val : val; // get absolute value of val

Here, absval will be assigned the value of val if val is zero or greater. If val is negative, then absval will be assigned the negative of that value (which yields a positive value).

Here is another example of the ? operator. This program divides two numbers, but will not allow a division by zero.

 // Prevent a division by zero using the ?. using System; class NoZeroDiv {   public static void Main() {     int result;     for(int i = -5; i < 6; i++) {       result = i != 0 ? 100 / i : 0;       if(i != 0)         Console.WriteLine ("100 / " + i + " is " + result);     }   } }  

The output from the program is shown here:

 100 / -5 is -20 100 / -4 is -25 100 / -3 is 33 100 / -2 is 50 100 / -1 is -100 100 / 1 is 100 100 / 2 is 50 100 / 3 is 33 100 / 4 is 25 100 / 5 is 20

Pay special attention to this line from the program:

 result = i != 0 ? 100 / i : 0;

Here, result is assigned the outcome of the division of 100 by i. However, this division takes place only if i is not zero. When i is zero, a placeholder value of zero is assigned to result.

You don't actually have to assign the value produced by the ? to some variable. For example, you could use the value as an argument in a call to a method. Or, if the expressions are all of type bool, the ? can be used as the conditional expression in a loop or if statement. For example, here is the preceding program rewritten a bit more efficiently. It produces the same output as before.

 // Prevent a division by zero using the ?. using System; class NoZeroDiv2 {   public static void Main() {        for(int i = -5; i < 6; i++)       if(i != 0 ? true : false)         Console.WriteLine("100 / " + i +                            " is " + 100 / i);   } }

Notice the if statement. If i is zero, then the outcome of the if is false, the division by zero is prevented, and no result is displayed. Otherwise the division takes place.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net