Combining Test Clauses


In the previous section you learned how to compare two value types and how to compare two reference types. A lot of times you will want to make more than one comparison.

To combine multiple clauses in the same statement:

  1. Type the first clause (for example, qty >= 0 ).

  2. Type one of the following operators: && for and, or for or.

  3. Type the second clause (for example, sItem != "" ) ( Figure 3.13 ).

    Figure 3.13 C# enables you to combine clauses with either && (for and) or (for or).
     int qty = 10; string item = "Computer"; bool ValidEntry = (  qty > 0 &&   item != ""  ); //true 

graphics/tick.gif Tips

  • When you use an and clause ( && ) both sides have to be true in order for the expression to be true; in the case of an or expression ( ) only one of the expressions needs to be true.

  • C# uses a system called short-circuiting . With short-circuiting if the program figures out that the expression will be true or false after evaluating part of the statement, it stops evaluating the rest of the expression. This happens if, for example, the first clause is false in an and expression. Since both of the clauses need to be true, having a single false makes the entire expression false, so there's no need to evaluate the second half. The same is true if one of the clauses is true in an or expression, since only one of the clauses needs to be true for the expression to be true ( Figure 3.14 ).

    Figure 3.14 In an && clause if one of the parts is false, then the whole expression is false. In an clause if one of the parts is true then the whole thing is true.
     class App {    bool Task1()    {      return true;    }    bool Task2()    {      return false;    }    void ProgramCode()    {      bool result1 = (  Task2()   && Task1()  );      //only Task2 is executed      bool result2 = (  Task1()   Task2()  );      //only Task1 is executed    } } 



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