Home » C# » If Else Statement in C# Example

If Else Statement in C# Example

Below are the examples of If-Else statement in C# and nested If-Else statements.

C# If Else Statement Example

using System;
class Values
{
    static void Main()
    {
        int valueOne = 10;
        int valueTwo = 20;
        if (valueOne > valueTwo)
        {
            Console.WriteLine(
            "ValueOne: {0} larger than ValueTwo: {1}",
            valueOne, valueTwo);
        }
        else
        {
            Console.WriteLine(
            "ValueTwo: {0} larger than ValueOne: {1}",
            valueTwo, valueOne);
        }
        valueOne = 30; // set valueOne higher
        if (valueOne > valueTwo)
        {
            valueTwo = valueOne + 1;
            Console.WriteLine("\nSetting valueTwo to valueOne value, ");
            Console.WriteLine("and incrementing ValueOne.\n");
            Console.WriteLine("ValueOne: {0} ValueTwo: {1}",
            valueOne, valueTwo);
        }
        else
        {
            valueOne = valueTwo;
            Console.WriteLine("Setting them equal. ");
            Console.WriteLine("ValueOne: {0} ValueTwo: {1}",
            valueOne, valueTwo);
        }
        Console.ReadLine();
    }
}

Output

ValueTwo: 20 larger than ValueOne: 10

Setting valueTwo to valueOne value,
and incrementing ValueOne.

ValueOne: 30 ValueTwo: 31

Nested If-Else Example

using System;
using System.Collections.Generic;
using System.Text;
namespace NestedIf
{
    class NestedIf
    {
        static void Main()
        {
            int temp = 32;
            if (temp <= 32)
            {
                Console.WriteLine("Warning! Ice on road!");
                if (temp == 32)
                {
                    Console.WriteLine(
                    "Temp exactly freezing, beware of water.");
                }
                else
                {
                    Console.WriteLine("Watch for black ice! Temp: {0}", temp);
                } // end else
            } // end if (temp <= 32)
            Console.ReadLine();
        } // end main
    } // end class
} // end namespace

Output

Warning! Ice on road!
Temp exactly freezing, beware of water.

See also: