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) ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.