The C# If else control statement has two blocks. One is a true block the other is a false block. In case condition in the if block is true, the statements in the if block is executed, if it is false, the else block statements are executed. The syntax of the C# If Else Statement is shown below.
if <condition> { Statements //These statements are executed if the condition is true } else { Statements //These statements are executed if the condition is false }
C# If Else Statement Example
Let us see an example of if else by finding whether the given input number is even or odd.
using System; namespace CSharp_Tutorial { class Program { static void Main() { Console.WriteLine("Please enter any Numeric Value "); int i = int.Parse(Console.ReadLine()); if (i % 2 == 0) { Console.WriteLine("{0} is even number", i); } else { Console.WriteLine("{0} is odd number", i); } } } }
In the above C# code, we have taken the integer variable i
Since Console.ReadLine() returns a string, and we explicitly convert it to an integer using Parse.int
The input number is given as 93
Since 93%2 = 1, the output is
93 is an odd number