Jim Jim - 1 month ago 27
C# Question

Inline switch / case statement in C#

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
}

Answer

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]();