Skip to content

Implicitly typed local variables C# 3.0code reductionreadability

Declare variables with `var` so the compiler infers the type.

Variable assignments are a common operation in C# and it can be quite frustrating to type the name of the type twice when creating new instances of objects (not to mention reading them over and over).

C# 3 reduces this duplication by allowing the type of the variable to be eliminated from the left-hand side by substituting the type with the var keyword. This indicates the compiler will figure it out based on the result type of the right-hand side.

Code

C#
var droid = new Droid("C3-PO", DroidType.Protocol);

var priorities = new Dictionary<int, string>();
C#
Droid droid = new Droid("C3-PO", DroidType.Protocol);

Dictionary<int, string> priorities = new Dictionary<int, string>();

Notes

  • You must use var when assigning from Anonymous types as they have no available type
  • var is still fully strong-typed - it simply is replaced by the compiler with the type from the right-hand-side
  • Consider whether to use var in other scenarios:
    • If the type is obvious from the assignment then var can reduce noise
    • If the type is unclear or confusing then using the actual type instead of var can make things clearer
    • If your variable should be a supertype or interface then explicitly typing it is clearer than a cast

INFO

Target-typed new C# 9.0 was introduced as an alternative to removing duplicate type names on assignment by eliminating it from the right-hand side of the assignment which allows for use in field initialization too.

More information