How to Use Var Pattern in C# for Simple Type Matching
In C#, the
var pattern is used in pattern matching to match any value and capture it into a new variable. You write it as var variableName inside a switch or is expression to get the value regardless of its type.Syntax
The var pattern captures any value and assigns it to a new variable. It is written as var variableName inside a pattern matching expression.
Parts explained:
var: keyword indicating any type is accepted.variableName: the name you choose to hold the matched value.
This pattern works with is expressions and switch expressions.
csharp
if (obj is var x) { // x holds the value of obj }
Example
This example shows how to use the var pattern to capture any value and print it, regardless of its type.
csharp
object[] items = { 42, "hello", 3.14, null };
foreach (var item in items)
{
if (item is var value)
{
Console.WriteLine($"Captured value: {value ?? "null"}");
}
}Output
Captured value: 42
Captured value: hello
Captured value: 3.14
Captured value: null
Common Pitfalls
One common mistake is to think var pattern checks for a specific type. It actually matches any value, so it always succeeds.
Another pitfall is using var pattern without a variable name, which is invalid.
Wrong usage example:
csharp
// This is invalid and causes a compile error // if (obj is var) { } // Correct usage: if (obj is var x) { Console.WriteLine(x); }
Quick Reference
Use the var pattern when you want to capture any value without caring about its type. It is useful in switch or is expressions to simplify code.
- Syntax:
var variableName - Matches: Any value, including
null - Use case: Capture and use the value without type checks
Key Takeaways
The var pattern matches any value and captures it into a new variable.
Use var pattern inside is or switch expressions to simplify value extraction.
You must provide a variable name after var; just var alone is invalid.
The var pattern always succeeds, so it is useful as a fallback or to capture values.
It works with any type, including null values.