Understanding Decisional Statements in C#


We start by saying that decisional statements (or constructs) are the most basic constructs in any programming language and C# is no exception. They give the programs a choice to use different blocks of code according to some conditions. The ability to construct dynamic and reactive applications that can deal with a number of situations and user inputs is important.

The most common decisional statements in C# are if, if else and nested if states. They serve a unique purpose in control of the flow of a program. It’s important to know how to use these statements correctly because as a developer you need to write efficient and logical code.

The if Condition

Decision making based on the if condition is the most basic form of decision making in C#. It allows user to execute a part of code if a specified condition result to true. It just skipped the code block if the condition is false and proceed to the next statement.

if (condition)
{
    // Code to execute if condition is true
}

There it is a boolean expression which the program has to evaluate. The statement inside the braces {} will only execute, if the condition becomes true. This streamlines simple decision making areas, such as validating user input or checking system states before some operation may be carried out.

Example for if

Imagine you’ve got to verify that the user over 18 has not accessed some content yet. You can use an if statement to perform this check:

int userAge = 20;

if (userAge >= 18)
{
    Console.WriteLine("Access granted. You are old enough.");
}

If condition is true then message access granted. You are old enough.” is displayed. If the userAge was smaller than 18 the program would not execute the code in the if block and instead would skip it and don’t print the message.

Tackling this simple use of an if statement to control program flow is simple and powerful. This makes sure that only when specific criteria are met one or more actions be executed, increasing its reliability and user experience.

The if-else Condition

The if statement can take care of situations where you’d like to run a set of code based on a true condition but the if-else statement enables you to execute a different action when the condition is false. It achieves that such a code block executes one of two if possible, therefore covering both results of your condition.

The syntax for an if-else statement is:

if (condition)
{
    // Code to execute if condition is true
}
else
{
    // Code to execute if condition is false
}

Yet that structure is also useful in cases where you want to take two explicit paths.

Example for if-else

Let’s modify our previous example to provide feedback regardless of the user’s age:

int userAge = 16;

if (userAge >= 18)
{
    Console.WriteLine("Access granted. You are old enough.");
}
else
{
    Console.WriteLine("Access denied. You are too young.");
}

With userAge equal to 16, the condition userAge == 18 will return false and the one below will as well: So the program runs the code in the else and shows ‘Access denied. You are too young.” This guarantees that the user gets the correct feedback whether she has any or not.

The if else statement, adds to the power of your program to make decisions when different result is required to its evaluation. It’s particularly useful for input validation, error handling and you can provide default actions.

Else If Condition

The else if actually enables the programmer to check a number of conditions without having to use a number of else’s. It comes in handy when more than two possible course of action can be followed based on certain condition. The program checks each condition one by one until one of the condition turns to true and then performs the code with that block.

The syntax for using else if is:

if (condition1)
{
    // Code to execute if condition1 is true
}
else if (condition2)
{
    // Code to execute if condition2 is true
}
else
{
    // Code to execute if none of the above conditions are true
}

This structure offer a means to address multiple situations, instead of using one if-else within another one.

Example for Else If

Suppose we want to categorize a person’s age group: This is because similar to computers Getis calculates the similarity ratio of a given area by comparing the attributes of a child, teenager, adult as well as senior against attributes of an ideal individual.

int age = 45;

if (age <= 12)
{
    Console.WriteLine("You are a child.");
}
else if (age > 12 && age <= 19)
{
    Console.WriteLine("You are a teenager.");
}
else if (age > 19 && age <= 64)
{
    Console.WriteLine("You are an adult.");
}
else
{
    Console.WriteLine("You are a senior.");
}

In this example, the program checks each condition sequentially:

  • age <= 12: Generates to false because 45 is not lesser than 12.
  • age > 12 && age <= 19: Returns to False since 45 which is greater than 19.
  • age > 19 && age <= 64: Between 19 and 64, 45 is true since it comes up to that.

As the third condition is true the corresponding message ‘You are an adult.’ is displayed. The program then continues outside this conditional construct without assessing any other conditions.

Nested Condition

Nested conditions refer to one condition being within the other so that if the first condition is true the second will be tested. This makes it possible to perform more sophisticated decision making scenarios provided a second condition exists and is based on the first condition being true.

if (condition1)
{
    if (condition2)
    {
        // Code to execute if both condition1 and condition2 are true
    }
}

As well, nested conditions can be combined with else or else if statements to establish convoluted decision trees.

Example for Nested Condition

Suppose we want to write a program that will determine if a user is eligible for a special membership discount depending their age, and membership status.

int age = 70;
bool isMember = true;

if (age >= 65)
{
    if (isMember)
    {
        Console.WriteLine("You are eligible for a senior member discount.");
    }
    else
    {
        Console.WriteLine("You are eligible for a senior discount, consider becoming a member for more benefits.");
    }
}
else
{
    if (isMember)
    {
        Console.WriteLine("Thank you for being a member.");
    }
    else
    {
        Console.WriteLine("Consider becoming a member to enjoy discounts.");
    }
}

In this example, the user will be either identified as 65+ which will satisfy the outer if clause, or will be age 13 – 64 containing the inner if clause. Condition age >= 65 results true since age is 70. The inner if statement then checks isMember and if that is true the program will then move to the last function.

The reason that isMember is true is that, since it is, the message “You are eligible for a senior member discount.” is displayed. The alternative message would appear in the inside else block of the if isMember was false.

The nested if – else part clause will be executed, if the age is less than 65, which contains another nested if – else to decide whether the user is a member or not for the younger age users.

What is a Ternary Operator?

C# ternary operator is simply a way to perform a conditional evaluation and it aids you to take decisions without having to write a full line of code for it. It is called “ternary” because it involves three operands: an input to evaluate and a result, depending on the input, being true or false. The syntax uses the ? and : it is a compact alternative to the traditional if-else statement because of symbols.

This operator makes code more readable and less change in code, especially the simple conditional assignments or expressions. When we want to condense multiple lines into one, the ternary operator comes handy, especially when the code we’re writing needs to be short and simple to read.

Basic Usage

The basic syntax of the ternary operator is:

condition ? expressionIfTrue : expressionIfFalse;

condition in this case is any expression which evaluates to Boolean value (true or false). Operator will return an expressionIfTrue if the condition is true, and will return an expressionIfFalse otherwise. After assigning this result to a variable, it can be used in a method call or even part of larger expressions.

For instance, let’s say you wish to insert a value to a variable depending on a condition then you might write an if … else statement. This can be simplified even further now that we’re using the ternary operator which makes our code cleaner and easier to maintain. However, still it is important that we use it judiciously to maintain the code readability, especially if this syntax is not known to the user of our code.

Example

Consider a scenario where you need to determine whether a number is positive or negative:

int number = -10;
string result = number >= 0 ? "Positive" : "Negative";
Console.WriteLine($"The number is {result}.");

In this case, the condition number >= 0 verifies if it’s positive or zero. If result is true then it would assign the string “Positive” and else assign “Negative.” Using an if else statement, we will need to have multiple lines, but this single line replaces it.

The number is Negative.

This shows that ternary operator is very useful to simplify code, and make the condition logic more simple. Single line but clear for very simple conditions.

Compound Ternary Expressions

Compound ternary expressions are used when you need to handle decision making process within one expression with multiple ternary operators inside or on another. It permits testing of several conditions and outcomes in a single but much more complicated line of code.

While using compound ternary expressions can definitely cut your lines of code, they can be hard to read and maintain if they’re used too deeply or too many of them. At the same time, we must balance conciseness with readability, and all of this so the code can still be understood by people who may read or maintain it should they come along later.

Example

Let’s illustrate a compound ternary expression by assigning a performance rating based on a score:

int score = 75;
string rating = score >= 90 ? "Excellent" :
                score >= 75 ? "Good" :
                score >= 60 ? "Average" :
                score >= 45 ? "Below Average" : "Poor";
Console.WriteLine($"Score: {score}, Rating: {rating}");

In this code, multiple conditions are evaluated in order:

  • If score >= 90, rating is "Excellent".
  • Else if score >= 75, rating is "Good".
  • Else if score >= 60, rating is "Average".
  • Else if score >= 45, rating is "Below Average".
  • Else, rating is "Poor".
Score: 75, Rating: Good

The first thing this compound ternary expression is doing away with a shower of if-else-if statements, and condensing the logic into a more compact form. But these expressions should be readable. Compound ternary operators can be formatted and indented properly such as above to make sense.

Conclusion

C# programming has some decisional statements like if, if-else and nested conditions. They give developers the flexibility to determine the flow of their applications according to the dynamic conditions providing them with more interactive and responsive applications to the user input.

Understanding, and handling effectively, these constructs allow you to write code that handles complex logic, and is able to handle different scenarios, gracefully. Decisional statements are necessary whether your input is being validated, access to resources being controlled, or the result of some calculation applied to multiple factors in your C# applications.

Use these statements and practice with them on different scenarios as you develop your programming skill to get better with logical thinking and problem solving in your code.

,