1536.md

February 3, 2022 ยท View on GitHub

Add a descriptive comment if the default block is supposed to be empty. Moreover, if that block is not supposed to be reached throw an InvalidOperationException to detect future changes that may fall through the existing cases. This ensures better code, because all paths the code can travel have been thought about.

void Foo(string answer)
{
	switch (answer)
	{
		case "no":
		{
		  Console.WriteLine("You answered with No");
		  break;
		}

		case "yes":
		{
		  Console.WriteLine("You answered with Yes");
		  break;
		}

		default:
		{
		  // Not supposed to end up here.
		  throw new InvalidOperationException("Unexpected answer " + answer);
		}
	}
}