0
0
C Sharp (C#)programming~5 mins

If-else execution flow in C Sharp (C#)

Choose your learning style9 modes available
Introduction

If-else helps your program make choices. It runs different code depending on conditions.

Deciding if a user is old enough to access a website
Checking if a number is positive or negative
Choosing what message to show based on the time of day
Turning on a light if it is dark outside
Syntax
C Sharp (C#)
if (condition)
{
    // code runs if condition is true
}
else
{
    // code runs if condition is false
}
The condition is a true or false question your program asks.
Only one block runs: either the if part or the else part.
Examples
This checks if age is 18 or more. It prints a message based on that.
C Sharp (C#)
int age = 18;
if (age >= 18)
{
    Console.WriteLine("You can vote.");
}
else
{
    Console.WriteLine("You are too young to vote.");
}
This checks if number is positive or not and prints accordingly.
C Sharp (C#)
int number = -5;
if (number > 0)
{
    Console.WriteLine("Positive number");
}
else
{
    Console.WriteLine("Zero or negative number");
}
Sample Program

This program asks the user for their age. It then uses if-else to print if they are an adult or a minor.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter your age: ");
        int age = int.Parse(Console.ReadLine() ?? "0");

        if (age >= 18)
        {
            Console.WriteLine("You are an adult.");
        }
        else
        {
            Console.WriteLine("You are a minor.");
        }
    }
}
OutputSuccess
Important Notes

Make sure the condition inside if is something that results in true or false.

You can have many if statements, but only one else per if.

Summary

If-else lets your program choose between two paths.

The if block runs when the condition is true.

The else block runs when the condition is false.