Inline switch / case statement in C#

40,227

Solution 1

If you want to condense things you could just put things on one line (let's imagine that "do one process is a call to Console.WriteLine):

switch (FIZZBUZZ)
{
    case "Fizz": Console.WriteLine("Fizz"); break;
    case "Buzz": Console.WriteLine("Buzz"); break;
    case "FizzBuzz": Console.WriteLine("FizzBuzz"); break;
}

If you want to get fancy you could create a map of strings to actions like this:

var map = new Dictionary<String, Action>
{
    { "Fizz", () => Console.WriteLine("Fizz") },
    { "Buzz", () => Console.WriteLine("Fizz") },
    { "FizzBuzz", () => Console.WriteLine("FizzBuzz") }
};

And then you could invoke the method like this:

map[FIZZBUZZ].Invoke(); // or this: map[FIZZBUZZ]();

Solution 2

Introduced in C# 8.

You can now do switch operations like this:

FIZZBUZZ switch
{
    "fizz"     => /*do something*/,
    "fuzz"     => /*do something*/,
    "FizzBuzz" => /*do something*/,
    _ => throw new Exception("Oh ooh")
};

Assignment can be done like this:

string FIZZBUZZ = "fizz";
string result = FIZZBUZZ switch
    {
        "fizz"     => "this is fizz",
        "fuzz"     => "this is fuzz",
        "FizzBuzz" => "this is FizzBuzz",
        _ => throw new Exception("Oh ooh")
    };
Console.WriteLine($"{ result }"); // this is fizz

Function calls:

public string Fizzer()     => "this is fizz";
public string Fuzzer()     => "this is fuzz";
public string FizzBuzzer() => "this is FizzBuzz";
...
string FIZZBUZZ = "fizz";
string result = FIZZBUZZ switch
    {
        "fizz"     => Fizzer(),
        "fuzz"     => Fuzzer(),
        "FizzBuzz" => FizzBuzzer(),
        _ => throw new Exception("Oh ooh")
    };
Console.WriteLine($"{ result }"); // this is fizz

Multiple inline-actions per case (delegates are a must I think):

string FIZZBUZZ = "fizz";
string result = String.Empty;
_= (FIZZBUZZ switch
{
    "fizz" => () =>
    {
        Console.WriteLine("fizz");
        result = "fizz";
    },
    "fuzz" => () =>
    {
        Console.WriteLine("fuzz");
        result = "fuzz";
    },
    _ => new Action(() => { })
});

You can read more about the new switch case here: What's new in C# 8.0

Solution 3

FYI, if anyone was looking for a inline shorthand switch case statement to return a value, I found the best solution for me was to use the ternary operator multiple times:

string Season = "Spring";
Season = Season == "Fall" ? "Spring" : Season == "Spring" ? "Summer" : "Fall";

You can optionally make it more readable while still inline by wrapping it in parens:

Season = (Season == "Fall" ? "Spring" : (Season == "Spring" ? "Summer" : "Fall"));

or by using multiple lines and indenting it:

Season = Season == "Fall" ? "Spring" 
       : Season == "Spring" ? "Summer" 
       : "Fall";

So, to serve as a code execution block you could write:

string FizzBuzz = "Fizz";
FizzBuzz = FizzBuzz == "Fizz" ? MethodThatReturnsAString("Fizz") : (FizzBuzz == "Buzz" ? MethodThatReturnsAString("Buzz") : MethodThatReturnsAString("FizzBuzz"));

Not the most respectable solution for a long list of case elements, but you are trying to do an inline switch statement ;)

Critiques from the community?

Solution 4

With the assumption that this is purely esoteric and that you will not be tempted to use this in a production system, you could abuse expression trees:

FIZZBUZZ.Switch(Fizz => DoSomething(),
                Buzz => DoSomethingElse(),
                FizzBuzz => DoSomethingElseStill());

Where Switch is an extension method:

public static void Switch(this string @this, params Expression<Action>[] cases)
{
    Expression<Action> matchingAction = cases.SingleOrDefault(@case => @case.Parameters[0].Name == @this);
    if (matchingAction == null) return; // no matching action
    matchingAction.Compile()();
}

Solution 5

In C# 8 you can do something like this

    public Form1()
    {
        InitializeComponent();
        Console.WriteLine(GetSomeString("Fizz"));
    }
    public static string GetSomeString(string FIZZBUZZ) =>
       FIZZBUZZ switch
       {
           "Fizz" => "this is Fizz",
           "Buzz" => "this is Buzz",
           "FizzBuzz" => "this is FizzBuzz",
           _ => "Unknown"
       };

This is equivalent to

    public static string GetSomeString(string FIZZBUZZ)
    {
        switch (FIZZBUZZ)
        {
            case "Fizz": return "this is Fizz";
            case "Buzz": return "this is Buzz";
            case "FizzBuzz": return "this is FizzBuzz";
            default: return "Unknown";
        }
    }
Share:
40,227
Jim
Author by

Jim

Full Stack Web Developer. I like knowing how all of the cogs that make the machine work.

Updated on March 18, 2020

Comments

  • Jim
    Jim almost 3 years

    I am on a weird kick of seeing how few lines I can make my code. Is there a way to condense this to inline case statements?

        switch (FIZZBUZZ)
        {
          case "Fizz":
            {
              //Do one process
              break;
            }
          case "Buzz":
            {
              //Do one process
              break;
            }
          case "FizzBuzz":
            {
              //Do one process
              break;
            }
        }
    

    to look something like this:

        switch (FIZZBUZZ)
        {
          case "Fizz": //Do one process
          case "Buzz": //Do one process
          case "FizzBuzz": //Do one process
        }