INTRODUCTION
The if statement is a so-called conditional statement. It allows you to branch your code depending on whether certain conditions are met or not. C# has two such conditional statements, the if statement and the switch statement. In this tutorial we will talk about the if statement, a frequent element of all programs.
SYNTAX AND USE
The if statement is a feature of all programming languages and their syntax is almost identical:
If (condition)
Statements;
If the condition of the if statement evaluates to true, the statement underneath it will execute. Otherwise, the program will continue from the next line. Only the following line is considered to be in the if statement. If you want to include more than one lines of code as a single block, you must use curly braces({}):
If (condition)
{
Statement1;
Statement2;
Other statements…;
}
It is also possible that you want to do something if the condition is false. In this case you have to add the else statement:
If (condition)
{
Statement1;
Statement2;
Other statements…;
}
Else
{
Else statements;
}
The above code checks the condition value. If it is true the first block of code will execute. If it is evaluated to false, the second block of code will execute. In case you need to have more than one else statements you can add as many else if statements as you like:
If (condition)
{
Statement1;
Statement2;
Other statements…;
}
Else if (condition2)
{
Else statements;
}
Else if (condition3)
{
Else statements;
}
Else if (condition4)
{
Else statements;
}
Notice that all condition statements must evaluate to Boolean values. This means you have to use equality and inequality statements or other type-checking mechanisms in your code. In C# the equality check is “==” while the assignment statement is “=”. If, by mistake instead of an equality check, you assign a value to a variable, this will not be a Boolean value, unless assigning a Boolean, and will return an error. The following snippet of code demonstrates an example of the if statement:
static void Main(string[] args)
{
string myInput;
myInput = Console.ReadLine();
if (myInput.Length < 10)
Console.WriteLine("The text contains less than 10 characters");
else if (myInput.Length > 9 && myInput.Length < 20)
Console.WriteLine("The text contains between 10 and 20 characters");
else
Console.WriteLine("The text contains more than 20 characters");
}
In this example we used the AND (&&) logical operator which takes two Boolean values and evaluates to true only if both of them are true. In our example the second condition statement will evaluate to true only if the length of the input string is bigger than 9 characters and less than 20 characters. Another common logical operator is the OR operator which evaluates to true when at least one of the two values is true.
discuss this topic to forum
