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

If statement execution flow in C Sharp (C#)

Choose your learning style9 modes available
Introduction

An if statement helps your program decide what to do based on a condition. It lets your program choose different paths, like making a choice in real life.

When you want to check if a number is positive or negative and do something different for each.
When you want to check if a user entered the correct password before allowing access.
When you want to decide what message to show based on the time of day.
When you want to perform an action only if a button is clicked.
When you want to check if a list is empty before processing it.
Syntax
C Sharp (C#)
if (condition)
{
    // code to run if condition is true
}
else
{
    // code to run if condition is false
}

The condition is a statement that is either true or false.

The else part is optional and runs only if the if condition is false.

Examples
This checks if number is greater than zero and prints a message if true.
C Sharp (C#)
int number = 10;
if (number > 0)
{
    Console.WriteLine("Number is positive");
}
This prints "Not positive" because the number is less than zero.
C Sharp (C#)
int number = -5;
if (number > 0)
{
    Console.WriteLine("Positive");
}
else
{
    Console.WriteLine("Not positive");
}
Checks a true/false condition and prints a message accordingly.
C Sharp (C#)
bool isRaining = true;
if (isRaining)
{
    Console.WriteLine("Take an umbrella");
}
else
{
    Console.WriteLine("No umbrella needed");
}
Sample Program

This program checks the temperature and prints if it is warm or cold.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        int temperature = 15;

        if (temperature > 20)
        {
            Console.WriteLine("It's warm outside.");
        }
        else
        {
            Console.WriteLine("It's cold outside.");
        }
    }
}
OutputSuccess
Important Notes

Only one block of code runs: either the if block or the else block.

You can have multiple if statements to check different conditions one after another.

Summary

An if statement lets your program choose between two paths.

The condition inside if must be true or false.

The else block runs only if the if condition is false.