Csharp if condition and

Selection statements — if , if-else , and switch

The if , if-else and switch statements select statements to execute from many possible paths based on the value of an expression. The if statement executes a statement only if a provided Boolean expression evaluates to true . The if-else statement allows you to choose which of the two code paths to follow based on a Boolean expression. The switch statement selects a statement list to execute based on a pattern match with an expression.

The if statement

An if statement can be any of the following two forms:

    An if statement with an else part selects one of the two statements to execute based on the value of a Boolean expression, as the following example shows:

DisplayWeatherReport(15.0); // Output: Cold. DisplayWeatherReport(24.0); // Output: Perfect! void DisplayWeatherReport(double tempInCelsius) < if (tempInCelsius < 20.0) < Console.WriteLine("Cold."); >else < Console.WriteLine("Perfect!"); >> 
DisplayMeasurement(45); // Output: The measurement value is 45 DisplayMeasurement(-3); // Output: Warning: not acceptable value! The measurement value is -3 void DisplayMeasurement(double value) < if (value < 0 || value >100) < Console.Write("Warning: not acceptable value! "); >Console.WriteLine($"The measurement value is "); > 

You can nest if statements to check multiple conditions, as the following example shows:

DisplayCharacter('f'); // Output: A lowercase letter: f DisplayCharacter('R'); // Output: An uppercase letter: R DisplayCharacter('8'); // Output: A digit: 8 DisplayCharacter(','); // Output: Not alphanumeric character: , void DisplayCharacter(char ch) < if (char.IsUpper(ch)) < Console.WriteLine($"An uppercase letter: "); > else if (char.IsLower(ch)) < Console.WriteLine($"A lowercase letter: "); > else if (char.IsDigit(ch)) < Console.WriteLine($"A digit: "); > else < Console.WriteLine($"Not alphanumeric character: "); > > 

In an expression context, you can use the conditional operator ?: to evaluate one of the two expressions based on the value of a Boolean expression.

The switch statement

The switch statement selects a statement list to execute based on a pattern match with a match expression, as the following example shows:

DisplayMeasurement(-4); // Output: Measured value is -4; too low. DisplayMeasurement(5); // Output: Measured value is 5. DisplayMeasurement(30); // Output: Measured value is 30; too high. DisplayMeasurement(double.NaN); // Output: Failed measurement. void DisplayMeasurement(double measurement) < switch (measurement) < case < 0.0: Console.WriteLine($"Measured value is ; too low."); break; case > 15.0: Console.WriteLine($"Measured value is ; too high."); break; case double.NaN: Console.WriteLine("Failed measurement."); break; default: Console.WriteLine($"Measured value is ."); break; > > 

At the preceding example, the switch statement uses the following patterns:

  • A relational pattern (available in C# 9.0 and later): to compare an expression result with a constant.
  • A constant pattern: test if an expression result equals a constant.
Читайте также:  Oracle create or replace and compile java

For information about the patterns supported by the switch statement, see Patterns.

The preceding example also demonstrates the default case. The default case specifies statements to execute when a match expression doesn’t match any other case pattern. If a match expression doesn’t match any case pattern and there’s no default case, control falls through a switch statement.

A switch statement executes the statement list in the first switch section whose case pattern matches a match expression and whose case guard, if present, evaluates to true . A switch statement evaluates case patterns in text order from top to bottom. The compiler generates an error when a switch statement contains an unreachable case. That is a case that is already handled by an upper case or whose pattern is impossible to match.

The default case can appear in any place within a switch statement. Regardless of its position, the default case is evaluated only if all other case patterns aren’t matched or the goto default; statement is executed in one of the switch sections.

You can specify multiple case patterns for one section of a switch statement, as the following example shows:

DisplayMeasurement(-4); // Output: Measured value is -4; out of an acceptable range. DisplayMeasurement(50); // Output: Measured value is 50. DisplayMeasurement(132); // Output: Measured value is 132; out of an acceptable range. void DisplayMeasurement(int measurement) < switch (measurement) < case < 0: case >100: Console.WriteLine($"Measured value is ; out of an acceptable range."); break; default: Console.WriteLine($"Measured value is ."); break; > > 

Within a switch statement, control can’t fall through from one switch section to the next. As the examples in this section show, typically you use the break statement at the end of each switch section to pass control out of a switch statement. You can also use the return and throw statements to pass control out of a switch statement. To imitate the fall-through behavior and pass control to other switch section, you can use the goto statement.

In an expression context, you can use the switch expression to evaluate a single expression from a list of candidate expressions based on a pattern match with an expression.

Case guards

A case pattern may be not expressive enough to specify the condition for the execution of the switch section. In such a case, you can use a case guard. That is an additional condition that must be satisfied together with a matched pattern. A case guard must be a Boolean expression. You specify a case guard after the when keyword that follows a pattern, as the following example shows:

DisplayMeasurements(3, 4); // Output: First measurement is 3, second measurement is 4. DisplayMeasurements(5, 5); // Output: Both measurements are valid and equal to 5. void DisplayMeasurements(int a, int b) < switch ((a, b)) < case (>0, > 0) when a == b: Console.WriteLine($"Both measurements are valid and equal to ."); break; case (> 0, > 0): Console.WriteLine($"First measurement is , second measurement is ."); break; default: Console.WriteLine("One or both measurements are not valid."); break; > > 

The preceding example uses positional patterns with nested relational patterns.

Читайте также:  Bootstrap docs min css

C# language specification

For more information, see the following sections of the C# language specification:

For more information about patterns, see the Patterns and pattern matching section of the C# language specification.

See also

Источник

C# — if, else if, else Statements

C# provides many decision-making statements that help the flow of the C# program based on certain logical conditions. Here, you will learn about if, else if, else, and nested if else statements to control the flow based on the conditions.

C# includes the following flavors of if statements:

C# if Statement

The if statement contains a boolean condition followed by a single or multi-line code block to be executed. At runtime, if a boolean condition evaluates to true, then the code block will be executed, otherwise not.

int i = 10, j = 20; if (i < j) < Console.WriteLine("i is less than j"); > if (i > j) < Console.WriteLine("i is greater than j"); > 

In the above example, a boolean condition in the first if statement i < j evaluates to true, so the C# compiler will execute the following code block. The second if statement's condition i >j evaluates to false, so the compiler will not execute its code block.

The conditional expression must return a boolean value, otherwise C# compiler will give a compile-time error.

int i = 10, j = 20; if (i + 1) < Console.WriteLine("i is less than j"); > if (i + j) < Console.WriteLine("i is greater than j"); > 

You can call a function in the if statement that returns a boolean value.

static void Main(string[] args) < int i = 10, j = 20; if (isGreater(i, j)) < Console.WriteLine("i is less than j"); > if (isGreater(j, i)) < Console.WriteLine("j is greater than i"); > > static bool isGreater(int i, int j) < return i > j; > 

else if Statement

Multiple else if statements can be used after an if statement. It will only be executed when the if condition evaluates to false. So, either if or one of the else if statements can be executed, but not both.

if(condition1) < // code block to be executed when if condition1 evaluates to true >else if(condition2) < // code block to be executed when // condition1 evaluates to flase // condition2 evaluates to true >else if(condition3) < // code block to be executed when // condition1 evaluates to flase // condition2 evaluates to false // condition3 evaluates to true >

The following example demonstrates else if statements.

int i = 10, j = 20; if (i == j) < Console.WriteLine("i is equal to j"); > else if (i > j) < Console.WriteLine("i is greater than j"); > else if (i < j) < Console.WriteLine("i is less than j"); > 

else Statement

The else statement can come only after if or else if statement and can be used only once in the if-else statements. The else statement cannot contain any condition and will be executed when all the previous if and else if conditions evaluate to false.

int i = 20, j = 20; if (i > j) < Console.WriteLine("i is greater than j"); > else if (i < j) < Console.WriteLine("i is less than j"); > else < Console.WriteLine("i is equal to j"); > 

Nested if Statements

C# supports if else statements inside another if else statements. This are called nested if else statements. The nested if statements make the code more readable.

if(condition1) < if(condition2) < // code block to be executed when // condition1 and condition2 evaluates to true >else if(condition3) < if(condition4) < // code block to be executed when // only condition1, condition3, and condition4 evaluates to true >else if(condition5) < // code block to be executed when // only condition1, condition3, and condition5 evaluates to true >else < // code block to be executed when // condition1, and condition3 evaluates to true // condition4 and condition5 evaluates to false >> >

The following example demonstrates the nested if else statements.

int i = 10, j = 20; if (i != j) < if (i < j) < Console.WriteLine("i is less than j"); > else if (i > j) < Console.WriteLine("i is greater than j"); > > else Console.WriteLine("i is equal to j"); 

Use Ternary operator ?: instead of a simple if else statement.

Читайте также:  Java stream api reduce

Источник

Оцените статью