Skip to content

var pattern

Context: The var pattern matches any expression and assigns it to a new variable. It is useful in switch expressions to capture the input.

object obj = "test";
if (obj is var x)
{
Console.WriteLine(x.GetType()); // always matches
}
string result = obj switch
{
int i => $"int: {i}",
string s => $"string: {s}",
var other => $"unknown: {other.GetType()}"
};

Logging the original value: In a switch expression, use var as the default case to capture the unmatched value for logging.

Example: In a logging middleware, you can log the actual value that didn’t match any pattern.