Pattern Matching in C#
Pattern matching in C# is a feature that allows for checking a value against a pattern. It is a more powerful feature than traditional switch statements or if-else conditions, as it can decompose values into parts and perform complex conditional logic with less code.
Pattern Matching in C# with Example
Pattern matching can be used in switch statements or expressions to simplify code that needs to perform checks against several different possible types or shapes of data. For example:
object obj = 42;
var result = obj switch {
int i when i > 0 => "Positive integer",
string s => $"String of length {s.Length}",
_ => "Unknown type"
};
Console.WriteLine(result);
C# Pattern Matching Multiple Values
C# allows pattern matching against multiple values by combining it with tuples in switch expressions, providing a neat way to handle complex logic.
var inputs = (3, "hello");
var output = inputs switch {
(3, string s) when s.Length > 3 => "Value is 3 and string is longer than 3 characters",
(_, string s) => $"String is {s}",
_ => "Unknown input"
};
Pattern Matching in C# Interview Questions
In interviews, you may be asked to demonstrate how pattern matching can be used to simplify decision-making processes in code or to discuss its benefits over other conditional logic forms.
- Question: How does pattern matching improve code readability?
- Answer: It reduces boilerplate by allowing conditions and actions to be expressed concisely.
C# Pattern Matching Type Switch
Using pattern matching in switch statements to handle different types dynamically is a robust feature. Here’s how you can use it to handle various object types differently:
object obj = new List<int> {1, 2, 3};
var typePattern = obj switch {
int i => $"Single integer: {i}",
IEnumerable<int> list => $"List with count: {list.Count()}",
_ => "Unknown object type"
};
C# Switch Pattern Matching Multiple Statements
In a switch expression, you can execute multiple statements for each case using pattern matching by encapsulating them in a method or a local function.
var response = 200;
var action = response switch {
200 => new Action(() => {
Console.WriteLine("OK");
LogResponse("200 OK");
}),
404 => new Action(() => Console.WriteLine("Not Found")),
_ => new Action(() => Console.WriteLine("Unknown Status"))
};
action();
C# Pattern Matching Generic Type
Pattern matching can be used with generic types by specifying the type in the pattern, allowing for type-specific operations within generic methods or classes.
public void LogMessage<T>(T message) {
var output = message switch {
int n => $"Integer: {n}",
string s => $"String: {s}",
_ => "Unknown type"
};
Console.WriteLine(output);
}
C# List Pattern Matching
C# 9.0 and later include support for list patterns in pattern matching, which can be particularly useful for decomposing lists or arrays in conditions.
var numbers = new[] { 1, 2, 3 };
var match = numbers switch {
[1, 2, 3] => "Matches the array [1, 2, 3]",
[1, .., 3] => "Starts with 1 and ends with 3",
_ => "Does not match"
};