C# > Core C# > Control Flow > switch Statement
Switch Statement with Pattern Matching (C# 7.0 and later)
This example demonstrates using switch statements with pattern matching, a feature introduced in C# 7.0, to handle different types of objects.
Code Snippet
This code demonstrates pattern matching in a switch statement. The `DescribeObject` method takes an `object` as input and uses pattern matching to determine its type. It then returns a descriptive string. Each `case` uses the `is` operator to check if the object is of a specific type and, if so, assigns it to a variable of that type. This allows you to work with the object as its specific type within the case. The `null` case handles null objects, and the `default` case handles any other types.
using System;
public class PatternMatchingExample
{
public static void Main(string[] args)
{
object obj = GetObject();
string message = DescribeObject(obj);
Console.WriteLine(message);
}
public static object GetObject()
{
Random random = new Random();
int choice = random.Next(1, 4); // Generates 1, 2, or 3
switch (choice)
{
case 1:
return 10;
case 2:
return "Hello";
case 3:
return new DateTime(2023, 10, 27);
default:
return null;
}
}
public static string DescribeObject(object obj)
{
switch (obj)
{
case int i:
return $"It's an integer: {i}";
case string s:
return $"It's a string: {s}";
case DateTime dt:
return $"It's a DateTime: {dt:yyyy-MM-dd}";
case null:
return "It's null";
default:
return "It's some other type";
}
}
}
Concepts Behind the Snippet
Pattern matching allows you to match an expression against different patterns. In the context of a switch statement, pattern matching allows you to switch on the type of an object and perform different actions based on the type. The `case` clause specifies the pattern to match, and the code associated with the case is executed if the pattern matches. This feature enhances the expressiveness and type-safety of C# code.
Real-Life Use Case
Pattern matching in switch statements is particularly useful when dealing with heterogeneous collections or APIs that return objects of different types. For example, processing events from different sources, handling different types of messages in a messaging system, or deserializing data from a file or network stream.
Best Practices
When to use them
Use pattern matching in switch statements when you need to handle objects of different types and perform different actions based on the type. This approach is cleaner and more maintainable than using multiple `if-else if-else` statements with `GetType()` calls.
Alternatives
Alternatives include using a series of `if-else if-else` statements with `is` operator checks, or using the Visitor pattern for more complex scenarios involving multiple object types and operations.
Pros
Cons
FAQ
-
What is the `when` clause used for in pattern matching?
The `when` clause allows you to add additional conditions to a pattern matching case. The case will only be executed if both the pattern matches and the condition in the `when` clause is true. This allows for more complex and nuanced matching logic. -
What happens if none of the patterns match?
If none of the patterns match, the `default` case will be executed. If there is no `default` case, nothing will happen, and execution will continue after the switch statement. It's generally good practice to always include a `default` case to handle unexpected situations. -
Is pattern matching supported in older versions of C#?
No, pattern matching in switch statements was introduced in C# 7.0. You will need to use a C# compiler version 7.0 or later to use this feature.