Utilizor
Contact Us

C# If...Else

Conditional statements.

C# If...Else

C# supports the usual logical conditions from mathematics:

  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to: a == b
  • Not equal to: a != b

You can use these conditions to perform different actions for different decisions.

Conditional Statements

C# has the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

Ternary Operator

There is also a short-hand if else, which is known as the ternary operator because it consists of three operands.

Syntax: variable = (condition) ? expressionTrue : expressionFalse;

Examples

The if Statement

Basic if condition.

using System;

class Program
{
  static void Main(string[] args)
  {
    if (20 > 18) 
    {
      Console.WriteLine("20 is greater than 18");
    }
  }
}

The else Statement

Executing code when condition is false.

using System;

class Program
{
  static void Main(string[] args)
  {
    int time = 20;
    if (time < 18) 
    {
      Console.WriteLine("Good day.");
    } 
    else 
    {
      Console.WriteLine("Good evening.");
    }
  }
}

The else if Statement

Handling multiple conditions.

using System;

class Program
{
  static void Main(string[] args)
  {
    int time = 22;
    if (time < 10) 
    {
      Console.WriteLine("Good morning.");
    } 
    else if (time < 20) 
    {
      Console.WriteLine("Good day.");
    } 
    else 
    {
      Console.WriteLine("Good evening.");
    }
  }
}

Ternary Operator

Short-hand if...else.

using System;

class Program
{
  static void Main(string[] args)
  {
    int time = 20;
    string result = (time < 18) ? "Good day." : "Good evening.";
    Console.WriteLine(result);
  }
}

Nested If

If statement inside another if statement.

using System;

class Program
{
    static void Main()
    {
        int x = 10;
        int y = 20;
        if (x == 10)
        {
            if (y == 20)
            {
                Console.WriteLine("Both conditions are true");
            }
        }
    }
}