var was introduced in C# 3.0 (NETFx 3.5). It infers a local variable type from the initializer, and that inferred type is still static at compile time.
Why it matters
varreduces repetition when the initializer already makes the type clear.varis required for anonymous types.- The compiler still enforces a concrete inferred type.
Cautions
- Avoid
varwhen it hides an important type detail. - Keep explicit types for public members and method signatures.
Explicit type vs var for obvious locals
When the right side already shows the concrete type, var removes duplication while keeping compile-time typing.
Valid since C# 3.0
Without var
Dictionary<string, List<decimal>> ordersByCustomer = new Dictionary<string, List<decimal>>();
With var
var ordersByCustomer = new Dictionary<string, List<decimal>>();
Anonymous type projection
Anonymous types have no type name, so var is the canonical declaration style.
Valid since C# 3.0
using System.Linq;
var metrics = new[]
{
new { Endpoint = "/health", DurationMs = 12 },
new { Endpoint = "/orders", DurationMs = 43 }
};
var slowEndpoints = metrics
.Where(metric => metric.DurationMs > 20)
.Select(metric => new { metric.Endpoint, metric.DurationMs });
Related features
Learn more
Newer capabilities
-
Target-typed `new`
Introduced in C# 9.0
Target-typed
newis a newer syntax option that can reduce repeated type names when the target type is already known.Dictionary<string, List<decimal>> trailingOrders = new();