Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# var Keyword Usage: Type Inference Explained

C# var declares a local variable without spelling out the type. Learn how type inference works, when var helps with LINQ and anonymous types, and when explicit types are clearer.

~4 min readC#
#C##Type Inference#Anonymous Types#LINQ
Illustration of C# var keyword usage showing type inference from a variable declaration to a concrete type

The C# var keyword lets you declare a local variable without spelling out its type. The compiler infers the type from the initializer expression. This behavior is called implicit typing. Understanding how var works is essential for writing idiomatic C# code, especially when working with LINQ and anonymous types.

What var Does and How Type Inference Works

When you write var x = 10;, the compiler determines that x is an int because the initializer is an integer literal. The resulting IL is identical to writing int x = 10;. var is not a dynamic type; it is a compile-time feature that replaces the type placeholder with the actual type during compilation.

The initializer must have a compile-time type. You cannot use var without an initializer, and you cannot assign null directly because null has no type. For example, var s = null; does not compile. You need a cast or a different approach.

csharp
var count = 42; // int var name = "Alice"; // string var items = new List<int>(); // List<int>

The compiler uses the static type of the initializer expression. If the expression is a method call, the return type is used. This means var never introduces a new type; it only hides the name.

Using var with Anonymous Types

One of the most common reasons to use var is to hold the result of an anonymous type expression. Anonymous types are created with new { ... } and have no explicit name. You must use var to store them because you cannot write the type name.

csharp
var person = new { Name = "Alice", Age = 30 }; Console.WriteLine($"{person.Name} is {person.Age} years old.");

Anonymous types are read-only and have value equality semantics. They are commonly produced by LINQ projections. Without var, you would have to define a separate class, which defeats the purpose of anonymous types.

var and LINQ Queries

LINQ queries often return IEnumerable<T> where T is an anonymous type or a complex generic type. Writing the full type explicitly is verbose and error-prone. var keeps the code readable while preserving the compile-time type.

csharp
var query = from p in products where p.Price > 100 select new { p.Name, p.Price };

The compiler infers that query is IEnumerable<AnonymousType>. You can iterate over it and access Name and Price with full IntelliSense support. If you later change the shape of the projection, the variable type updates automatically, which reduces maintenance overhead.

Readability and Maintainability Tradeoffs

var can improve readability when the type is obvious from the initializer, such as var customer = new Customer();. It can hurt readability when the type is not obvious, for example var result = GetData(); where GetData returns a complex type that is not evident from the method name.

The C# coding guidelines in many teams recommend using var when the type is visible on the right side of the assignment, and explicit types when it is not. This is a heuristic, not a hard rule. The goal is to make the code self-documenting without forcing the reader to jump to the method definition.

Consider these two declarations:

csharp
var settings = ConfigurationManager.GetSettings(); ConfigurationSettings settings = ConfigurationManager.GetSettings();

The explicit version communicates the type immediately. The var version requires the reader to know the return type of GetSettings. In a large codebase, that extra cognitive load adds up.

When Explicit Types Are Better

There are situations where explicit types are preferable. If the initializer is a numeric literal, the type is clear, but if the initializer is a method call or a property access, the type may be ambiguous. Explicit types also serve as documentation for the intent of the variable.

Another case is when you want to ensure a specific interface is used. For example, if you have a method that returns List<T> but you want to treat it as IEnumerable<T>, you should declare the variable explicitly.

csharp
IEnumerable<int> numbers = GetNumbers(); // returns List<int>

Using var would give you List<int>, which changes the behavior if you later modify the list. Explicit typing lets you control the contract.

var and the dynamic Keyword: A Common Misconception

Some developers confuse var with dynamic. They are fundamentally different. var is resolved at compile time and the variable has a static type. dynamic defers type checking to runtime and can cause runtime exceptions if the member does not exist.

csharp
dynamic d = GetValue(); d.SomeMethod(); // runtime binding var v = GetValue(); v.SomeMethod(); // compile-time binding

Using dynamic disables IntelliSense and can lead to runtime errors. var does not. You should not use dynamic as a substitute for var when you want type inference. The main use cases for dynamic are COM interop and interoperability with dynamic languages.

Compatibility and Coding Standards

var is a C# 3.0 feature, so it is available in all modern .NET versions. It works in local variables only; you cannot use it for class fields, properties, or method return types. Those require explicit types.

Many teams adopt a coding standard that dictates when to use var. For example, the default in the .NET documentation is to use var when the type is apparent, but some teams prefer explicit types everywhere for consistency. The important thing is to agree on a rule and apply it consistently. If you are working on a legacy codebase, follow the existing style.

Another common use of var is in a foreach loop. You can use var there just as you would with a local variable.

csharp
foreach (var item in collection) { // item type is inferred from collection element type }

This is common and safe.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.