C#: If Else

The if else statement is a conditional branch statement.

If you are new to programming, this will be one of the first things that you should learn.

We can illustrate it by using the below statements:

if (expression)
  {
    statement 1;
  }
  else
  {
    statement 2;
  }

The expression is actually a Boolean expression.  It should resolve to either true or false.

If the expression resolves to true, statement 1 will be run.  If the expression resolves to false, statement 2 will be run.

Since the expression is a Boolean expression, let’s use the example below where it will check if a Boolean variable is set to true or false.

using System;

namespace Conditional
{
    class Program
    {
        static void Main()
        {
            bool test = false;

            if (test)
            {
                Console.WriteLine("The test boolean variable is set to true.");
            }
            else
            {
                Console.WriteLine("The test boolean variable is set to false.");
            }
            Console.ReadLine();
        }
    }
}

In line 11, we have if (test).

This is actually similar to if (test == true) as shown in the example below, with the minor modification.

If Else
using System;

namespace Conditional
{
    class Program
    {
        static void Main()
        {
            bool test = false;

            if (test == true)
            {
                Console.WriteLine("The test boolean variable is set to true.");
            }
            else
            {
                Console.WriteLine("The test boolean variable is set to false.");
            }
            Console.ReadLine();
        }
    }
}

 

 

Series Navigation<< C#: Passing parameters into a constructor
C#: The while statement >>