Question Details

No question body available.

Tags

c# c++

Answers (17)

May 19, 2026 Score: 3 Rep: 50,918 Quality: Low Completeness: 40%

IMO, the code snippet you provide looks less readable than an if-else block. Keep it clear and simple. You already have an option to use if-else, the compiler will do the best optimization for you. Microoptimization isn't required here.

May 19, 2026 Score: 3 Rep: 26,413 Quality: Low Completeness: 0%

No, please don't. C++ is bloated enough already.

May 18, 2026 Score: 2 Rep: 58,173 Quality: Low Completeness: 0%

You should submit a proposal to the C++ committee.

May 19, 2026 Score: 2 Rep: 135,171 Quality: Low Completeness: 40%

nothing wrong with an if-else block. there is. This is exhaustive pattern matching (like that found in TypeScript, F#, Python, etc), not a chain of if-else. Missing conditions cause a compiler error. You can match on type and properties, not just values

May 19, 2026 Score: 1 Rep: 135,171 Quality: Medium Completeness: 80%

This is an example of pattern matching, not just if-else and there are several proposals for it using the match keyword. It's not available yet in C++. This article describes various alternatives.

Pattern matching is available in a lot of languages, including C#, TypeScript, F#, Python, Rust, and more. It's used for safety and simplicity, not just to eliminate keystrokes. Using it can eliminate entire class hierarchies, visitors etc. Adding it to C++ isn't a new effort. Bjarne Stroustrup was involved in earlier implementation going back to 2014. The latest proposal would allow code like this :

int getarea(const Shape& shape) {
  return shape match {
    Circle: let [r] => 3.14 * r * r;
    Rectangle: let [w, h] => w * h;
  };
}

or

p match {
  [0, 0]     => std::print("on origin");
  [0, let y] => std::print("on y-axis at {}", y);
  [let x, 0] => std::print("on x-axis at {}", x);
  let [x, y] => std::print("at {}, {}", x, y);
};

BTW wildcards are discouraged in all languages because they disable compile-time checking. A better version of the C# code would be the following, which doesn't depend on evaluation order :

var value = rand.Next(10) switch 
{
     "apple (30%)",
    (>=3) and ( "banana (40%)",
    >=7 => "orange (30%)"
};

Pattern matching is a very powerful concept. It matches the value against a pattern that can include the type, property values, container values, relations like the one shown here. It's available in multiple languages eg TypeScript, Python, F#, Go, Rust etc. Combined with destructuring

In Rust you can specify cases based on types or object properties :

    let p = Point { x: 0, y: 7 };

match p { Point { x, y: 0 } => println!("On the x axis at {x}"), Point { x: 0, y } => println!("On the y axis at {y}"), Point { x, y } => { println!("On neither axis: ({x}, {y})"); } }

One of the most common examples is the Result pattern used in Rust, F#, Go (and more). It's possible to specify that a type can be one of several options (but none other) and match on it, enforcing that all options are covered. That's something that can't be enforced with inheritance. Eg in Rust :

enum Result {
   Ok(T),
   Err(E),
}

...

let version = parseversion(&[1, 2, 3, 4]); match version { Ok(v) => println!("working with version: {v:?}"), Err(e) => println!("error parsing header: {e:?}"), }

If another type is added, the compiler generate an error until all match clauses are fixed to include it.

This is a special case of union types, one of the most requested, if not THE most requested feature in C# syntax for a decade. (It's already available in other languages). Once C# 15 arrives in November 2026, we'll be able to write :

public record class Cat(string Name);
public record class Dog(string Name);
public record class Bird(string Name);

public union Pet(Cat, Dog, Bird); ... string name = pet switch { Dog d => d.Name, Cat c => c.Name, Bird b => b.Name, };

If you read Result and think REST API results, yes. That's a big motivator too.

May 19, 2026 Score: 1 Rep: 135,171 Quality: Low Completeness: 60%

This is pattern matching, not if-else, and there's already a proposal using the match keyword

May 19, 2026 Score: 1 Rep: 71,233 Quality: Low Completeness: 0%

"If one line of Regex does not solve your problem, your line isn't long enough."

May 19, 2026 Score: 1 Rep: 135,171 Quality: Low Completeness: 10%

It's not a matter of opinion - this is pattern matching, not an if-else alternative. That's the term you need to find in C++. BUT a huge benefit of pattern matching is exhaustiveness supported by the compiler itself. Older C++ versions definitely don't support exhaustive matching.

May 19, 2026 Score: 1 Rep: 135,171 Quality: Low Completeness: 10%

It's not less readable at all and far safer - matching is exhaustive, the compiler itself will complain if a case isn't covered.

This is pattern matching, a functional programming concept also found in TypeScript, Python and F#. This is a trivial case. More complex cases match by type, property and even container data.

May 19, 2026 Score: 1 Rep: 1 Quality: Low Completeness: 10%

I personally think it makes it more readable, but I suppose that is, in-fact, a matter of my own opinion as well. I just find C++ switch statements a little lackluster, not even just in lacking C# switch expressions; if I understand correctly, most C++ compilers use jump tables, which makes sense as to why they feel lacking to me, as most of my experience is in high-level languages with a little bit in assembly, so I guess I'm just not used to a language in-between.

May 19, 2026 Score: 1 Rep: 1 Quality: Low Completeness: 10%

I wouldn't say I'm trying to avoid it, I'm just very comfortable with C# and love switch expressions from it. This is an interesting solution, I'll have to dive into that rabbit hole at some point, thank you!

May 18, 2026 Score: 0 Rep: 58,173 Quality: Low Completeness: 30%

The only type of switch statement in C++ is using integral compile-time constants for the case label. Not strings, only integral compile-time constants.

May 19, 2026 Score: 0 Rep: 49,061 Quality: Low Completeness: 50%

It really depends what you want to do. But there is nothing wrong with an if-else block. Not sure why you want to avoid it.

However in this specific case, if-else could be avoided thus:

// Random Number Generator
std::mt19937 prng{std::randomdevice{}()};

std::string value = std::array { "apple (30%)", "banana (40%)", "orange (30%)" } [std::discrete
distribution({30, 40, 30})(prng)];

std::println("value: {}", value);

May 19, 2026 Score: 0 Rep: 8,610 Quality: Low Completeness: 30%

How can it be less readable when if statements make me read more characters? Eh? EH?

May 19, 2026 Score: 0 Rep: 550,409 Quality: Low Completeness: 60%

FYI you’re seeding prng incorrectly, since the state of mt19937 is larger than what std::random_device{} gives you. Here’s how to seed std::mt19937 correctly.

May 19, 2026 Score: 0 Rep: 286,328 Quality: Low Completeness: 30%

He's asking about expressions, not statements. Closest thing in standard C++ right now is the ternary condition? if-true: if-false operator.

May 19, 2026 Score: 0 Rep: 1,382 Quality: Low Completeness: 60%

I feel like the conversation here got derailed into pattern matching, the actual question is about switch expressions, which in C# are less like a switch statement, and more like a generalization of the ternary operator.

The point is to produce a value from each of the cases (as opposed to execute one or more statements)

Honestly, yes, I would love to have both features (pattern matching and switch expressions) and while they play nicely together, they are distinct features.

While reflection + annotations can probably produce a cleaner answer in C++ 26, imagine:

enum class Fruit { apple, banana, grape }; std::string GetComboboxValue(Fruit fruit) { return std::format("({}): {}", staticcast(fruit), // Replaces cascading ?: expressions here and eliminates the need for placeholder variables from a cascading if. fruit switch { Fruit::apple => "A delicious apple", Fruit::banana => "A ripe banana", Fruit::grape => "A juicy grape", => "Naugty -- that isn't a fruit!" }); }