C# Var Pattern — Complete Guide
In this tutorial, you'll learn about C# Var Pattern. We cover key concepts, practical examples, and best practices.
You are pattern matching and need to use the matched value inside the expression arm. You write a type pattern and then repeat the variable assignment. The var pattern captures the value into a new variable in one step.
Wrong
if (obj is int i)
{
UseValue(i); // Already captured — this is fine for if
}
// But in a switch expression:
string result = obj switch
{
int i => ProcessInt(i), // OK
string s => ProcessString(s), // OK
_ => "unknown"
};
Output: Works, but when you need the original value without type-restricting it, or when you want to capture the value in a property pattern, you need the var pattern.
Right
public string Describe(object obj) => obj switch
{
var x => $"Got {x?.GetType().Name ?? "null"}"
};
Output: "Got String" for a string, "Got null" for null.
The var pattern always matches and assigns the value to a new variable. It is especially useful in property patterns:
public string Process(Point p) => p switch
{
{ X: var x, Y: var y } => $"At ({x}, {y})",
_ => "Unknown"
};
In a when clause, use var to capture intermediate calculations:
var result = input switch
{
var x when x.Length > 100 => "Long",
var x => $"Short: {x}"
};
Prevention
- Use
varpatterns when you need to reference the matched value inside the expression arm. - Use
varin property patterns to capture individual properties:{ Name: var n }. - Use
varto avoid repeating a computation inwhenclauses. - Use
varwith discards when you do not need the value:var _. - Do not overuse
var— use specific type patterns when you need type safety.
Common Mistakes with var pattern
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
The var pattern is used throughout DodaTech products for flexible pattern matching. For more C#, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro