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}In switch expressions
Section titled “In switch expressions”string result = obj switch{ int i => $"int: {i}", string s => $"string: {s}", var other => $"unknown: {other.GetType()}"};Real-world usage example
Section titled “Real-world usage example”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.