Inline switch / case statement in C#
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]();
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
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?