Conditional Operator


Many times in programming you want to set the contents of a variable to one value if the condition is true, or to another value if the condition if false. For example, consider the following code.

 string status; if (qty > 0)   status = "Available"; else   status = "Unavailable"; 

Notice that status could be available or unavailable depending on the value of qty. In C# these five lines of code can be condensed into a single line of code using the conditional operator (? :) .

To use the conditional operator:

  1. Enter the name of the variable you would like to set followed by an equal sign. For example: string status> = .

  2. Enter a Boolean expression in parentheses. For example: (qty > 0) .

  3. After the close parenthesis type a question mark ?.

  4. Type the resulting value if the expression evaluates to true. For example: "Available" .

  5. Type a colon : .

  6. Type the resulting value if the expression evaluates to false. For example: "Unavailable" .

  7. Type a semicolon ; ( Figure 3.24 ).

    Figure 3.24 The conditional operator makes it handy to combine an "if " and an "else" clause in a single statement. If qty is greater than zero, then the status will be available, otherwise it will be unavailable. Be careful not to abuse this technique. To beginning developers, it's often easier to read an if-else statement than the conditional operator.
     int qty = 10; string status = (qty > 0) ?        "Available" : "Unavailable"; 

graphics/tick.gif Tip

  • Instead of having literal values for the results you could use variables or invoke a function ( Figure 3.25 ).

    Figure 3.25 You aren't limited to using literals with the conditional operator; it also works with functions and variables.
     int balance = 20; int withdrawal = 30; int amount = (balance > withdrawal) ?  MakeWithdrawal()  :  BorrowFromSavings()  ; string managers = "Joe;Jane;Jill;John"; string everyone = managers + ";Rick;Sue"; bool managersOnly = true; string meeting = (managersOnly) ?  managers  :  everyone  ; 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

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