Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Use Switch Expressions Instead of Switch Statements

- 07.06.26 - ErcanOPAK

➡️ switch expression is an expression, not a statement

Switch statements are verbose. Switch expressions return values. Less code, fewer bugs, no fall-through.

❌ Switch Statement

string GetGrade(int score)
{
    string grade;
    switch (score)
    {
        case >= 90:
            grade = "A";
            break;
        case >= 80:
            grade = "B";
            break;
        default:
            grade = "F";
            break;
    }
    return grade;
}

✅ Switch Expression

string GetGrade(int score) => score switch
{
    >= 90 => "A",
    >= 80 => "B",
    _ => "F"
};

🎯 Advanced Patterns

// Tuple pattern
static string GetQuadrant((int x, int y) point) => point switch
{
    (0, 0) => "Origin",
    ( > 0, > 0) => "Q1",
    ( < 0, > 0) => "Q2",
    ( < 0, < 0) => "Q3",
    ( > 0, < 0) => "Q4",
    _ => "On axis"
};

// Type pattern + property pattern
static decimal CalculateDiscount(object item) => item switch
{
    Product { Category: "Electronics", Price: > 1000 } p => p.Price * 0.10m,
    Product { Category: "Books" } p => p.Price * 0.15m,
    Product p => p.Price * 0.05m,
    null => 0,
    _ => throw new ArgumentException()
};

// When guard
static string Classify(int number) => number switch
{
    < 0 => "Negative",
    0 => "Zero",
    > 0 and < 10 => "Small positive",
    >= 10 and < 100 => "Medium positive",
    _ => "Large positive"
};

💡 Benefits

  • Expression body (no statements)
  • No fall-through bugs (=> handles it)
  • Exhaustiveness checking (compiler warns if missing cases)
  • Can be used in LINQ, lambdas, initializers
  • Much less code, same logic

“50-line switch statement became 10-line switch expression. Removed all ‘break’ bugs. Compiler checks exhaustiveness. Switch expressions are how C# should have always worked.”

— C# Developer

Related posts:

How to get formatted JSON in C#

C# Async Methods Still Block Threads

ASP.NET Core “Slow Startup” — Reflection Scanning Trap

Post Views: 2

Post navigation

C#: Use ^ and .. for Indexing from End and Ranges
Visual Studio: Sync Settings Across Multiple Computers

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

June 2026
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930  
« May    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (953)
  • How to add default value for Entity Framework migrations for DateTime and Bool (882)
  • Get the First and Last Word from a String or Sentence in SQL (838)
  • How to select distinct rows in a datatable in C# (808)
  • How to make theater mode the default for Youtube (804)
  • Add Constraint to SQL Table to ensure email contains @ (580)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (579)
  • Average of all values in a column that are not zero in SQL (538)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (505)
  • Find numbers with more than two decimal places in SQL (454)

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files
  • Ajax: Add Custom Headers to Fetch Requests
  • JavaScript: Use console.table to Display Arrays as Tables
  • HTML: Use Spellcheck Attribute to Enable Browser Spell Check
  • CSS: Use user-select to Prevent Text Selection
  • Windows 11: Use Snipping Tool for Instant Screenshots

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (953)
  • How to add default value for Entity Framework migrations for DateTime and Bool (882)
  • Get the First and Last Word from a String or Sentence in SQL (838)
  • How to select distinct rows in a datatable in C# (808)
  • How to make theater mode the default for Youtube (804)

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com