11.2 Conditional statements using the if and else keywords


11.2 Conditional statements using the if and else keywords

The use of these keywords in conditional statements is identical in Java and C#. There follows some examples for completeness. Feel free to skip this section if you are already familiar with writing conditional statements using these keywords in Java.

Below is an example usage of if and else in conditional statements. It is self-explanatory.

 30:  public static void ConditionalDemo(int i){ 31:    if (i==0){ 32:      Console.WriteLine("is a zero"); 33:    } 34:    else if (i==1){ 35:      Console.WriteLine("is a one"); 36:    } 37:    else { 38:      Console.WriteLine("is not a zero or one"); 39:    } 40:  } 

Like Java

  • You can omit the curly braces if there is only one statement within your conditional block:

     31:  if (i==0) 32:    Console.WriteLine("is a zero"); 

    is as good as:

     31:  if (i==0){ 32:    Console.WriteLine("is a zero"); 33:  } 
  • Like while , the if construct accepts only a boolean value, or expressions which will evaluate to a boolean. if does not take in integral values. [4]

    [4] In C/C++, the if construct can take in integral values or expressions that evaluate to integral values. Zero is considered 'false' and any other integer is considered 'true'. In C/C++, statements such as if (1) instead of if (true) are considered legal.

You may have seen the use of #if and #else in C# (or C/C++ codes) “ these special keywords which start with a hex sign are called preprocessor directives, and are used only by the compiler during compilation. Preprocessor directives are not converted into IL code during compilation (see Chapter 24).



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

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