C# If-Else Statement

Programming in general often requires a decision or a branch within the code to account for how the code operates under different inputs or conditions. Within the C# programming language (and most programming languages for this matter), the simplest and sometimes the most useful way of creating a branch within your program is through an If-Else statement.

Lets assume we have method (a.k.a. a function) which takes an int parameter which will represent a score up to 100, and the method will print out a message saying whether we pass or fail.

static void PrintPassOrFail(int score)

{

if (score >= 50) // If score is greater or equal to 50

{

Console.WriteLine("Pass!");

}

else // If score is not greater or equal to 50

{

Console.WriteLine("Fail!");

}

}

When looking at this method, you may notice this line of code (score >= 50) inside the If statement. This can be seen as a boolean condition, where if the condition is evaluated to equal true, then the code that is in between the if { } is ran.

READ ALSO
C# Exception Handling Best Practices

For example, if this method was called like this: PrintPassOrFail(60);, the output of the method would be a Console Print saying Pass! since the parameter value of 60 is greater or equal to 50.

However, if the method was called like: PrintPassOrFail(30);, the output of the method would print out saying Fail!. This is because the value 30 is not greater or equal to 50, thus the code in between the else { } is ran instead of the If statement.

In this example, we’ve said that score should go up to 100, which hasn’t been accounted for at all. To account for score not going past 100 or possibly dropping below 0, see the If-Else If-Else Statement example.