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
}
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
No you can't.
The switch statement or switch case in java is a multi-way branch statement. Based on the value of the expression given, different parts of code can be executed quickly. The given expression can be of a primitive data type such as int, char, short, byte, and char.
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
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]();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With