C# Language Keywords if, if...else, if... else if

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example


The if statement is used to control the flow of the program. An if statement identifies which statement to run based on the value of a Boolean expression.

For a single statement, the braces{} are optional but recommended.

int a = 4;
if(a % 2 == 0) 
{
     Console.WriteLine("a contains an even number");
}
// output: "a contains an even number"

The if can also have an else clause, that will be executed in case the condition evaluates to false:

int a = 5;
if(a % 2 == 0) 
{
     Console.WriteLine("a contains an even number");
}
else
{
     Console.WriteLine("a contains an odd number");
}
// output: "a contains an odd number"

The if...else if construct lets you specify multiple conditions:

int a = 9;
if(a % 2 == 0) 
{
     Console.WriteLine("a contains an even number");
}
else if(a % 3 == 0) 
{
     Console.WriteLine("a contains an odd number that is a multiple of 3"); 
}
else
{
     Console.WriteLine("a contains an odd number");
}
// output: "a contains an odd number that is a multiple of 3"

Important to note that if a condition is met in the above example , the control skips other tests and jumps to the end of that particular if else construct.So, the order of tests is important if you are using if .. else if construct

C# Boolean expressions use short-circuit evaluation. This is important in cases where evaluating conditions may have side effects:

if (someBooleanMethodWithSideEffects() && someOtherBooleanMethodWithSideEffects()) {
  //...
}

There's no guarantee that someOtherBooleanMethodWithSideEffects will actually run.

It's also important in cases where earlier conditions ensure that it's "safe" to evaluate later ones. For example:

if (someCollection != null && someCollection.Count > 0) {
   // ..
}

The order is very important in this case because, if we reverse the order:

if (someCollection.Count > 0 && someCollection != null) {

it will throw a NullReferenceException if someCollection is null.



Got any C# Language Question?