C# Keywords Tutorial Part 42: if
Amr Saafan
Founder | CTO | Software Architect & Consultant | Engineering Manager | Project Manager | Product Owner | +28K Followers | Now Hiring!
In C#, the “if” keyword is a crucial control statement that allows you to conditionally execute code based on an expression or a set of expressions. In this article, we will delve into the “if” keyword in C# and offer examples to assist you in comprehending its functionality.
Syntax of the “if” keyword:
The syntax of the “if” keyword in C# is straightforward. Here is an example of how to use it:
if (condition)
{
? // Code to execute if the condition is true
}
In this code, the “condition” is an expression that evaluates to either true or false. If the condition is true, the code within the curly braces will execute. If the condition is false, the code within the curly braces will not execute.
Example 1: Simple “if” statement
领英推荐
int num = 10;
if (num > 5)
{
? Console.WriteLine("The number is greater than 5");
}
In this example, the “if” statement checks whether the value of the variable “num” is greater than 5. If the condition is true, the message “The number is greater than 5” will be displayed in the console.
Example 2: “if else” statement
int num = 3;
if (num > 5)
{
? Console.WriteLine("The number is greater than 5");
}
else
{
? Console.WriteLine("The number is less than or equal to 5");
}
In this example, the “if” statement checks whether the value of the variable “num” is greater than 5. If the condition is true, the message “The number is greater than 5” will be displayed in the console. If the condition is false, the code within the “else” block will execute, and the message “The number is less than or equal to 5” will be displayed in the console.
Example 3: “if else if” statement
int num = 10;
if (num > 10)
{
? Console.WriteLine("The number is greater than 10");
}
else if (num == 10)
{
? Console.WriteLine("The number is equal to 10");
}
else
{
? Console.WriteLine("The number is less than 10");
}
In this example, the “if” statement checks whether the value of the variable “num” is greater than 10. If the condition is true, the message “The number is greater than 10” will be displayed in the console. If the condition is false, the “else if” statement will check whether the value of the variable “num” is equal to 10. If the condition is true, the message “The number is equal to 10” will be displayed in the console. If both conditions are false, the code within the “else” block will execute, and the message “The number is less than 10” will be displayed in the console.