Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
Does C# have any equivalent to Elixir's `cond`?

In Elixir, if I want to check multiple boolean conditions, rather than some ugly mess of if/else logic, I can elegantly do this:

guess = 46
number_of_guesses = 3
cond do
   number_of_guesses > 5 -> 
      IO.puts "Too many guesses!  You lose."

   guess == 46 -> 
      IO.puts "You guessed 46!"

   guess == 42 -> 
      IO.puts "You guessed 42!"

   true        -> 
      IO.puts "I give up."
end

The above program generates the following result −

You guessed 46!

(Example derived from Tutorialspoint, but further contrived to demonstrate not every expression must contain the same variable.)

Does C# have anything similar or would I need to use if/else?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

If you are matching against a value in almost all of the cases, you can still use a switch expression, with case guards:

int guess = 46;
int numberOfGuesses = 3;
Console.WriteLine(
    guess switch {
        _ when numberOfGuesses > 5 => "Too many guesses!  You lose.",
        46 => "You guessed 46!",
        42 => "You guessed 42!",
        _ => "I give up."
    }
);

Notice that in the first arm, I matched anything (the underscore _ pattern) but only "when numberOfGuesses > 5". Or in this case you can even do fancier pattern matching:

Console.WriteLine(
    (guess, numberOfGuesses) switch
    {
        (_, > 5) => "Too many guesses!  You lose.",
        (46, _) => "You guessed 46!",
        (42, _) => "You guessed 42!",
        _ => "I give up."
    }
);

But of course, this is not possible in every situation.

If all the arms are unrelated conditions, using this sort of _ when ... construct feels a bit abusive, so alternatively, you can use a chain of ternary operators:

var x = 
    condition1 ?
        someValue1 :
    condition2 ?
        someValue2 :
    condition3 ?
        someValue3 :
    valueWhenNoConditionsAreTrue;

Though I feel even this can be a bit astonishing on first sight.

If you want to execute statements in those branches, rather than expressions, then you should just use a plain-old if-else-if structure, or if pattern matching can be used, a switch statement (but note that the _ when ... trick can't be used in a switch statement).

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!