If and Else Statement

C#While writing a program, we encounter such situations where we need to decide whether a certain block of code should be executed or not if a certain condition is met. For this purpose, we make use of If and Else statement, which is known as conditional statement. A sample code is given below with its explanation.

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 2;

            if (number == 1)
            {
                Console.WriteLine("The number is 1.");
            }
            else
            {
                Console.WriteLine("Unknown number.");
            }
        }
    }
}

In the above code, we have assigned a value 1 to the number variable.  With the help of If and Else statement, we have made a check for a certain condition before executing the code.  If the number value is 2, then the line #13 will be executed else line #17 will be executed.

Output:

Unknown number.

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •