404 Not Found

404 Not Found


nginx

Conditionals

The if Statement

The if statement executes a code block based on the result of a boolean expression. When the condition is true, the block runs; when false, it is skipped.

CSHARP
int score = 85;
if (score >= 60)
{
    Console.WriteLine("Passed");
}
TEXT
Passed

The if...else Statement

Use if...else to execute one branch when the condition is true and another when it is false.

CSHARP
int age = 16;
if (age >= 18)
{
    Console.WriteLine("Adult");
}
else
{
    Console.WriteLine("Minor");
}
TEXT
Minor

if...else if Multiple Branches

When you need to check several mutually exclusive conditions, use else if to test them in order. Only the first matching branch executes.

CSHARP
int score = 78;
if (score >= 90)
{
    Console.WriteLine("Excellent");
}
else if (score >= 80)
{
    Console.WriteLine("Good");
}
else if (score >= 60)
{
    Console.WriteLine("Pass");
}
else
{
    Console.WriteLine("Fail");
}
TEXT
Pass

Nested if

if statements can be nested, but try to keep nesting to no more than two levels. Deep nesting hurts readability - consider extracting a method or using else if instead.

Example

CSHARP
int age = 25;
bool hasTicket = true;
if (age >= 18)
{
    if (hasTicket)
    {
        Console.WriteLine("Admitted");
    }
    else
    {
        Console.WriteLine("Ticket required");
    }
}
else
{
    Console.WriteLine("Too young");
}
▶ Try it Yourself
TEXT
Admitted

The switch Statement

A switch statement matches an expression against multiple constant values and executes the corresponding case branch. Unlike C/C++, C# does not allow fall-through; each case must end with break, return, or throw, or a compile error occurs.

Example

CSHARP
int day = 3;
switch (day)
{
    case 1:
        Console.WriteLine("Monday");
        break;
    case 2:
        Console.WriteLine("Tuesday");
        break;
    case 3:
        Console.WriteLine("Wednesday");
        break;
    case 4:
        Console.WriteLine("Thursday");
        break;
    case 5:
        Console.WriteLine("Friday");
        break;
    default:
        Console.WriteLine("Weekend");
        break;
}
▶ Try it Yourself
TEXT
Wednesday

Multiple cases can share the same logic by listing their labels consecutively:

CSHARP
int month = 2;
switch (month)
{
    case 12:
    case 1:
    case 2:
        Console.WriteLine("Winter");
        break;
    case 3:
    case 4:
    case 5:
        Console.WriteLine("Spring");
        break;
    default:
        Console.WriteLine("Other season");
        break;
}
TEXT
Winter

Tip: In C#, if you genuinely need to jump from one case to another, you must use goto case x; omitting break for fall-through is not allowed.

Switch Expressions (C# 8+)

C# 8 introduced switch expressions, which are expressions rather than statements. They return the matched result with a more concise syntax. Use _ for the default branch.

Example

CSHARP
int code = 404;
string message = code switch
{
    200 => "OK",
    301 => "Moved",
    404 => "Not Found",
    500 => "Server Error",
    _ => "Unknown"
};
Console.WriteLine(message);
▶ Try it Yourself
TEXT
Not Found

Pattern Matching Basics

Starting with C# 7, you can use pattern matching in conditional logic. Common forms include type patterns (is Type variable) and when guards.

Example

CSHARP
object obj = "Hello C#";
if (obj is string s)
{
    Console.WriteLine($"String length: {s.Length}");
}
else
{
    Console.WriteLine("Not a string");
}
▶ Try it Yourself
TEXT
String length: 8

Use a when guard in a switch to add extra conditions:

CSHARP
int value = 15;
string category = value switch
{
    int i when i > 100 => "Extra large",
    int i when i > 10 => "Medium",
    int i when i > 0 => "Small",
    _ => "Invalid"
};
Console.WriteLine(category);
TEXT
Medium

The Conditional Operator ?:

The conditional operator ?:, also known as the ternary operator, is a shorthand for if...else. The syntax is condition ? valueIfTrue : valueIfFalse, and the entire expression evaluates to the corresponding value.

Example

CSHARP
int age = 20;
string status = age >= 18 ? "Adult" : "Minor";
Console.WriteLine(status);
▶ Try it Yourself
TEXT
Adult

Nested usage (avoid excessive nesting):

CSHARP
int score = 75;
string result = score >= 90 ? "A" : score >= 60 ? "B" : "C";
Console.WriteLine(result);
TEXT
B

Warning: Readability drops sharply when the conditional operator is nested more than two levels deep. Use if...else if statements instead.

❓ FAQ

Q Can C# switch statements omit break for fall-through like in C?
A No. C# prohibits switch fall-through. Each case must end with break, return, or throw, or a compile error occurs. To share logic, list multiple case labels consecutively.
Q What is the difference between a switch expression and a switch statement?
A A switch expression is an expression that must return a value, using => and comma-separated arms. A switch statement is a statement that does not require a return value, using case/break blocks.
Q What is the difference between is and ==?
A == compares values for equality, while is is used for pattern matching and can check the type while declaring a variable, such as obj is string s.
Q Can the conditional operator replace all if...else?
A No. The conditional operator only works in scenarios that return a value and cannot contain multiple statements. Use if...else for complex logic.

📖 Summary

📝 Exercises

  1. Write a program that reads an integer and determines whether it is positive, negative, or zero, then outputs the result
  2. Use a switch expression to map a month (1-12) to its corresponding season name
  3. Write a program that receives an object variable, uses is pattern matching to determine its type (int, string, or other), and outputs the type and value
  4. Use the conditional operator to convert a numeric score to a letter grade (90+ is A, 80+ is B, 60+ is C, otherwise D), then compare readability with an if...else if version
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏