C# switch expression tutorial in C# - With real world example

Beginning with C# 7.0, you use the switch expression to evaluate a single expression from a list of candidate expressions based on a pattern match with an input expression.

Since C# 1.0, you can write switch statements in your code. You usually do this instead of writing if/else if/else logic like you see it in the code snippet below.{alertInfo}

public void Debug_Old(bool? state)
{
	string message = string.Empty;
	switch (state)
	{
		case true:
			message = "Debug Enabled";
			break;
		case false:
			message = "Debug Disabled";
			break;
		default:
			message = "Invalid";
			break;

	}
	Console.WriteLine(message);


}

Let’s write the same code using the switch expression.

void Debug(bool? state)
{

	var message = state switch
	{
		true => "Debug Enabled", //_arms_
		false => "Debug Disabled",
		_ => "Invalid State" //case guard
	};

	Console.WriteLine(message);
}

The preceding example shows the basic elements of a switch expression:
You can also write the same program as below

void Debug(bool? state)
{

	Console.WriteLine(state switch
	{
		true => "Debug Enabled",
		false => "Debug Disabled",
		_ => "Invalid State"
	});

}

Note

  • Default case must be the last statement
  • If you do not cover all the cases compiler will give you a warning; for example, if you only check for a true case.

Note how all the case and break clutter went away and how readable it is. A case in a switch expression is a so-called switch expression arm:

Using the object in switch case before C# 7.0 is not supported

Before C# 7.0

So, you see, before C# 7.0, you can only use bool, char, string, integral types like int and float, enumerations, and corresponding nullable types. But you can’t switch by a object variable.

error CS0151: A switch expression of type `object’ cannot be converted to an integral type, bool, char, string, enum or nullable type{alertError}

After C# 7.0

Real-world example.

Let’s write some real-world code with switch expression.

Example 1- FizzBuzz

This is a prevalent interview question. Let's write the program using the c# new feature.

string FizzBuzz(int i)
{
	return (i % 3, i % 5) switch
	{
		(0, 0) => "FizzBuzz",
		(0, _) => "Fizz",
		(_, 0) => "Buzz",
		_ => i.ToString()

	};
}

Recursive switch expression

public int Factorial(int n)
{
	return n switch
	{
	    1 => 1,
		_ => n * Factorial(n - 1)
	};
}

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post