Implicitly typed locals (`var`)

C# 3.0 NETFx 3.5

Published Updated Author Jeffrey T. Fritz Reading time

Use var for obvious local types and anonymous types while keeping compile-time static typing.

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

  • var reduces repetition when the initializer already makes the type clear.
  • var is required for anonymous types.
  • The compiler still enforces a concrete inferred type.

Cautions

  • Avoid var when 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 });

Learn more

Implicitly typed local variables (Microsoft Learn)

Newer capabilities

  1. Target-typed `new`

    Introduced in C# 9.0

    Target-typed new is a newer syntax option that can reduce repeated type names when the target type is already known.

    Dictionary<string, List<decimal>> trailingOrders = new();