Pattern Matching is a feature that allows developers to check whether a value matches a specific type, constant, condition, or structure. Introduced in C# 7.0 and enhanced in later versions, pattern matching simplifies conditional logic by allowing developers to check values against patterns and optionally capture matching values.
- Allows checking types and extracting values without separate casting operations.
- Improves code readability by combining multiple conditions and simplifying if and switch statements.
Example: Program to demonstrate how pattern matching checks whether an object contains a string and displays it in uppercase.
using System;
class Geeks{
static void Main(){
object value = "Geeks for Geeks";
// Check whether the value is a string
if (value is string message){
Console.WriteLine(message.ToUpper());
}else{
Console.WriteLine("Not a string");
}
}
}
Output
GEEKS FOR GEEKS
Explanation:
- value is string message checks whether the object contains a string and assigns it to message.
- message.ToUpper() converts the matched string to uppercase.
- If the value is not a string, the else block executes.
Syntax of Pattern Matching
Pattern matching can be used with the is operator, switch statement, and switch expression.
1. Using the is Operator
The is operator checks whether an expression matches a specified pattern and returns a Boolean result.
if (expression is pattern){
// Code when the pattern matches
}
2. Using the switch Statement
The switch statement executes a block of code based on the first matching case.
switch (expression){
case pattern1:
// Code
break;
case pattern2:
// Code
break;
default:
// Default code
break;
}
3. Using the switch Expression
A switch expression evaluates patterns and returns a value from the first matching arm.
var result = expression switch{
pattern1 => value1,
pattern2 => value2,
_ => defaultValue
};
Here, _ is a discard pattern that matches any value not handled by earlier patterns.
Types of Patterns
C# supports different types of patterns for matching values, types, properties, and data structures.
1. Type and Declaration Patterns
A type pattern checks whether a value matches a specified type. A declaration pattern also assigns the matching value to a variable.
Example: Program to demonstrate how a declaration pattern checks an object's type and accesses its value.
using System;
class Geeks{
static void Main(){
object data = 100;
// Check the type and capture the value
if (data is int number)
{
Console.WriteLine("Integer: " + number);
}
}
}
Output
Integer: 100
Syntax
expression is TypeName
expression is TypeName variableName
- TypeName checks whether the value matches the specified type.
- TypeName variableName also captures the matched value.
The type-only pattern was introduced in C# 9, while declaration patterns have been supported since C# 7.
2. Constant Pattern
A constant pattern checks whether an expression matches a specified constant value, such as a number, character, string, enum constant, or null.
Example: Program to demonstrate how a constant pattern matches a number with the corresponding day of the week.
using System;
class Geeks{
static void Main(){
int day = 5;
string result = day switch
{
1 => "Sunday",
2 => "Monday",
3 => "Tuesday",
4 => "Wednesday",
5 => "Thursday",
6 => "Friday",
7 => "Saturday",
_ => "Invalid day"
};
Console.WriteLine(result);
}
}
Output
Thursday
Syntax
expression is constantValue
Explanation: This example uses custom day numbering, where 1 represents Sunday and 7 represents Saturday.
3. Relational Pattern
Relational patterns compare a value against a constant using <, <=, >, or >=. They were introduced in C# 9.
Example: Program to demonstrate how relational patterns identify whether a number is positive, negative, or zero.
using System;
class Geeks{
static void Main(){
int number = -15;
string result = number switch
{
< 0 => "Negative",
0 => "Zero",
> 0 => "Positive"
};
Console.WriteLine(result);
}
}
Output
Negative
Syntax
expression is < constant
expression is <= constant
expression is > constant
expression is >= constant
These patterns are useful for checking ranges, comparing numeric values, and simplifying conditional expressions.
4. Property Pattern
Property patterns check the values of properties or fields within an object. They allow multiple conditions to be evaluated without accessing each member separately.
Example: Program to demonstrate how a property pattern checks the length of a string.
using System;
class Geeks{
static void Main(){
string text = "Geeks";
// Check the Length property
if (text is { Length: 5 }){
Console.WriteLine("String has 5 characters");
}
}
}
Output
String has 5 characters
Syntax
expression is { PropertyName: pattern }
For multiple properties:
expression is { Property1: pattern1, Property2: pattern2 }
Property patterns were introduced in C# 8 and can combine several property checks in a single expression.
5. Positional Pattern
Positional patterns match values based on their positions. They are commonly used with tuples, positional records, and types that support deconstruction.
Example: Program to demonstrate how a positional pattern determines the location of a point using its coordinates.
using System;
class Geeks{
static void Main(){
var point = (0, 10);
string location = point switch
{
(0, 0) => "Origin",
(0, _) => "Y-axis",
(_, 0) => "X-axis",
_ => "Other location"
};
Console.WriteLine(location);
}
}
Output
Y-axis
Syntax
expression is (pattern1, pattern2)
- Each positional pattern checks the corresponding element or deconstructed value.
- _ matches any value at that position without capturing it.
6. Var Pattern
The var pattern matches any value, including null, and assigns it to a local variable. It is useful when a value needs to be captured for further processing.
Example: Program to demonstrate how a var pattern captures the result of an expression.
using System;
class Geeks{
static void Main(){
int number = 20;
if (number * 2 is var result)
{
Console.WriteLine(result);
}
}
}
Output
40
Syntax
expression is var variableName
The captured variable can be used in subsequent operations without explicitly specifying its type.
7. List Pattern
List patterns were introduced in C# 11. They check the length, elements, or structure of supported sequence types, such as arrays and List<T>.
Example: Program to demonstrate how a list pattern checks the first and last elements of an array.
using System;
class Geeks{
static void Main(){
int[] numbers = { 10, 20, 30, 40 };
// Match the first and last elements
if (numbers is [10, .., 40])
{
Console.WriteLine("Pattern matched");
}
}
}
Output
Pattern matched
Syntax
expression is [pattern1, pattern2, ...]
For matching a variable number of elements:
expression is [firstPattern, .., lastPattern]
They check the length, elements, or structure of supported sequence types, such as arrays and List.
Pattern Combinators
Pattern combinators were introduced in C# 9 to combine multiple patterns into a single condition. They make conditional statements easier to read and reduce the need for complex logical expressions.
C# supports three pattern combinators: not, and, and or.
1. not Pattern
The not pattern matches when the specified pattern does not match. It is useful for checking whether a value is different from a particular value or condition.
Example: Program to demonstrate how the not pattern checks whether a number is non-zero.
using System;
class Geeks{
static void Main(){
int number = 10;
// Check if the number is not zero
if (number is not 0)
{
Console.WriteLine("Number is non-zero");
}
else
{
Console.WriteLine("Number is zero");
}
}
}
Output
Number is non-zero
Syntax
expression is not pattern
2. and Pattern
The and pattern matches when both specified patterns are satisfied. It is commonly used to check whether a value falls within a particular range.
Example: Program to demonstrate how the and pattern checks whether a student's marks fall within a specified range.
using System;
class Geeks{
static void Main(){
int marks = 85;
// Check if marks are between 80 and 100
if (marks is >= 80 and <= 100){
Console.WriteLine("Grade A");
}else{
Console.WriteLine("Other Grade");
}
}
}
Output
Grade A
Syntax
expression is pattern1 and pattern2
3. or Pattern
The or pattern matches when at least one of the specified patterns is satisfied. It is useful when multiple values should produce the same result.
Example: Program to demonstrate how the or pattern checks whether a selected day is a weekend.
using System;
class Geeks{
static void Main(){
string day = "Sunday";
// Check if the day is Saturday or Sunday
if (day is "Saturday" or "Sunday")
{
Console.WriteLine("Weekend");
}
else
{
Console.WriteLine("Weekday");
}
}
}
Output
Weekend
Syntax
expression is pattern1 or pattern2
These combinators can also be used with property, positional, relational, and other compatible patterns to express complex conditions.
Variable Declaration and Discard Patterns
Pattern matching also supports variable declarations and discard patterns to capture useful values or ignore unnecessary ones.
1. Variable Declaration Pattern
A declaration pattern checks whether a value matches a specified type and assigns the matched value to a new variable.
Example: Program to demonstrate how a declaration pattern checks an object's type and stores its value in a variable.
using System;
class Geeks{
static void Main(){
object value = 50;
// Check type and capture the value
if (value is int number)
{
Console.WriteLine(number);
}
}
}
Output
50
Explanation:
- value is int number checks whether the object contains an integer and assigns it to number.
- Console.WriteLine(number) displays the captured integer value.
2. Discard Pattern
The discard pattern (_) matches any value without assigning it to a variable. It is commonly used to handle remaining cases in switch expressions.
Example: Program to demonstrate how a discard pattern handles values that do not match a specific case.
using System;
class Geeks{
static void Main(){
int number = 8;
// Match the number using a switch expression
string result = number switch
{
0 => "Zero",
_ => "Non-zero"
};
Console.WriteLine(result);
}
}
Explanation:
- 0 => "Zero" returns "Zero" when the number is zero.
- _ => "Non-zero" matches all remaining values.
- Console.WriteLine(result) displays the matched result.
A discard is useful for handling remaining cases or ignoring values that are not needed. Pattern variables cannot be declared inside not or or patterns, but they can be used in appropriate and patterns.
Nested Patterns
Nested patterns allow one pattern to contain other patterns. They are useful when checking multiple properties or conditions within an object.
Example: Program to demonstrate how nested property and relational patterns check a person's age.
using System;
class Person
{
public int Age { get; set; }
}
class Geeks{
static void Main(){
Person person = new Person { Age = 25 };
// Nested relational pattern
if (person is { Age: >= 18 and < 60 }){
Console.WriteLine("Working-age adult");
}
}
}
Output
Working-age adult
Explanation:
- { Age: ... } accesses the Age property through a property pattern.
- >= 18 and < 60 checks whether the age falls within the specified range.
- The message is displayed when both conditions are satisfied.
Advantages of Pattern Matching
Pattern matching provides several benefits when implementing conditional logic:
- Improves code readability by expressing type checks and conditional operations in a clear and concise way.
- Reduces the need for explicit casting when checking and capturing values of specific types.
- Simplifies complex conditional statements by using patterns with switch expressions and logical combinators.
- Makes it easier to work with tuples, records, objects, and collections by checking their structure and values.
- Helps organize conditional logic into separate cases, making code easier to understand and maintain.
Limitations of Pattern Matching
Although pattern matching simplifies conditional operations, it has some limitations:
- Complex nested patterns can become difficult to read when too many conditions are combined into one expression.
- Some pattern features require newer C# language versions, so they may not work in older projects.
- Pattern matching cannot replace every conditional expression, especially when conditions involve unrelated values or operations.
- A switch expression that does not handle every possible value can throw a SwitchExpressionException at runtime.
Difference Between Traditional Conditional Statements and Pattern Matching
Basis | Traditional Conditional Statements | Pattern Matching |
|---|---|---|
Syntax | Uses if, else, and conventional switch conditions | Uses patterns with is, switch statements, and switch expressions |
Type Checking | May require separate type checking and casting | Can combine type checking and value extraction |
Multiple Conditions | Uses logical operators such as && and \|\| | Supports and, or, and not pattern combinators |
Object Properties | Commonly accesses properties directly | Supports property and nested patterns |
Readability | Can become lengthy with complex conditions | Often makes supported conditions more concise |