skip to content

In C#, is a local declared with var dynamically typed, and where does the compiler refuse to accept var?

level: juniorimportance: must knowfreq 75%

answer

  1. decided once, by the compiler
  2. the initializer supplies the type
  3. a literal's suffix matters
  4. locals only, never fields
  5. null has no type

basics

~20 s

A var local is statically typed: the compiler infers one fixed type from the initializer, exactly as if you had written it. var works only on initialized locals; fields, null initializers, multiple declarators and bare array initializers are rejected.

solid answer

~40 s

`var` is compile-time type inference, not dynamic typing. The compiler reads the initializer and gives the local that type for good, so `var total = 0;` is an `int`, and a later `total += 12.5m;` fails with CS0266 because `decimal` has no implicit conversion to `int`. Members are checked at compile time exactly as with an explicit type. The compiler refuses `var` where there is nothing to infer from: an uninitialized local (CS0818), `var x = null;` (CS0815), two declarators in one statement (CS0819), a bare array initializer (CS0820), a collection expression (CS9176) and an overloaded method group (CS8917). Fields can never use it (CS0825). Since C# 10 a lambda has a natural type, so `var f = () => 42;` compiles.

code

csharp · 14 lines
csharp
using System;
using System.Collections.Generic;

var employees = new List<string> { "Ada", "Lin" };
var headcount = employees.Count;
var gross = 0m;
var rate = 0.2;
var bonus = () => 150m;

Console.WriteLine(employees.GetType().Name);
Console.WriteLine(headcount.GetType().Name);
Console.WriteLine(gross.GetType().Name);
Console.WriteLine(rate.GetType().Name);
Console.WriteLine(bonus.GetType().Name);

go deeper

for a junior

Recall that var is inferred once at compile time from the initializer, then list the places it is illegal: no initializer, null, fields, multiple declarators, array initializers.

for a middle

Explain how the initializer's literal type flows into the local, why 0 gives int and 0.2 gives double, and which CS errors the compiler raises for each var misuse.

for a senior

Show you can review var in real code: spot a literal that infers int or double where decimal was meant, and apply a team convention that keeps types visible when they are not obvious.

for a principal

A var policy is a readability choice with no run-time effect; pin it in .editorconfig with IDE0007 and IDE0008 so reviews stop relitigating it.

## What `var` really means `var` is a **contextual keyword** that asks the compiler to infer the type of a local variable from its initializer. The inference happens once, at compile time, and the result is an ordinary **static type**: the local is compiled exactly as if you had written that type yourself, so the IL is the same, the IDE shows the inferred type, and every member access is checked by the compiler. Nothing about the variable is decided at run time. A local declared with `var` can never change type later; assigning a value of another type is a compile error such as **CS0029** ("Cannot implicitly convert type 'string' to 'int'"). This is the first thing an interviewer checks, because a candidate who reads `var` as run-time typing will also misread every code review comment about it. ## The payroll review: the initializer picks the type In a payroll import routine the trap is rarely `var` itself; it is the **literal** that `var` copies its type from. The compiler applies the normal rules for literal and expression types: | Initializer | Inferred type | |---|---| | `0` | `int` | | `0m` | `decimal` | | `0.2` | `double` | | `0.2f` | `float` | | `0L` | `long` | | `new List<string>()` | `List<string>` | | `employees.Count` | `int` | | `() => 150m` | `Func<decimal>` (C# 10 and later) | Two lines a reviewer should flag: - `var total = 0;` followed by `total += line.Amount;` where `Amount` is a `decimal`. `total` is an `int`, and the compound assignment fails with **CS0266** ("Cannot implicitly convert type 'decimal' to 'int'. An explicit conversion exists (are you missing a cast?)"). The fix is `var total = 0m;` or `decimal total = 0;`. - `var rate = 0.2;` followed by `gross * rate` with a `decimal` gross. `rate` is a `double`, and C# has no implicit conversion between `double` and `decimal`, so the multiplication fails with **CS0019** ("Operator '*' cannot be applied to operands of type 'decimal' and 'double'"). Both are caught by the compiler, because `var` does not move any type check to run time, but they show why the suffix on a literal matters more once the type name is gone. ## Where the compiler refuses `var` `var` needs an initializer whose type the compiler can determine on its own. The .NET 10 SDK reports: - **CS0818** for `var b;`: "Implicitly-typed variables must be initialized". - **CS0815** for `var a = null;`: "Cannot assign <null> to an implicitly-typed variable", because `null` has no type. - **CS0819** for `var c = 1, d = 2;`: "Implicitly-typed variables cannot have multiple declarators". - **CS0820** for `var arr = { 1, 2 };`: "Cannot initialize an implicitly-typed variable with an array initializer"; write `new[] { 1, 2 }` instead. - **CS9176** for `var xs = [1, 2];`: "There is no target type for the collection expression." - **CS8917** for `var m = Console.WriteLine;`: "The delegate type could not be inferred.", because that method group has many overloads. - **CS0825** for a field such as `private var rates = new List<decimal>();`: "The contextual keyword 'var' may only appear within a local variable declaration or in script code". The field rule follows from how the compiler works: it records every field's type before it processes any initializer, so a field cannot wait for its initializer to be analysed. The local declarations in `for`, `foreach` and `using` statements may use `var`. One rule changed in **C# 10**: lambdas, and method groups that contain a single method, gained a **natural type**, so `var bonus = () => 150m;` compiles as `Func<decimal>`. An older programming-guide page still says a `var` local cannot be initialized with an anonymous function; the C# 14 compiler accepts it. ## `var` is not `object` or `dynamic` `var` is the opposite of both. `object` is an explicit static type that exposes only `object`'s own members; `dynamic` postpones member binding until run time. `var` simply writes the inferred type for you, and the code behaves exactly as if that type were spelled out. ## When to write `var` `var` is **required** when the type has no name you can write: an anonymous type such as `new { Name = "Ada", Net = 3_100m }`, or a LINQ query that projects into one. Everywhere else it is a style choice. The C# coding conventions recommend: 1. Use `var` when the type is obvious from the right side: a `new` expression, an explicit cast or a literal. 2. Write the type when it is not apparent, and do not rely on a method name to imply it. Teams enforce the choice with the `IDE0007` ("Use `var` instead of explicit type") and `IDE0008` ("Use explicit type instead of `var`") style rules, tuned by `csharp_style_var_for_built_in_types`, `csharp_style_var_when_type_is_apparent` and `csharp_style_var_elsewhere` in `.editorconfig`. And because `var` is contextual, a type actually named `var` in scope would turn `var x = ...` into a declaration of that type: one more sign that the compiler resolves `var`, never the runtime.

  • Why does `var rate = 0.2;` break a payroll calculation that multiplies a `decimal` gross by it?
    The literal `0.2` is a `double`, so `rate` is a `double`. C# has no implicit conversion between `double` and `decimal`, so `gross * rate` fails with CS0019 ("Operator '*' cannot be applied to operands of type 'decimal' and 'double'"). The fix is the `m` suffix, `var rate = 0.2m;`, or writing `decimal rate = 0.2m;`. With `var`, the literal's suffix is the only thing choosing the type.
  • When is `var` required rather than a style choice?
    When the initializer has an anonymous type, such as `new { Name = "Ada", Net = 3_100m }` or a LINQ projection into one. That type has no name you can write, so `var` (including `foreach (var row in query)`) is the only way to declare the local and still reach its properties. Everywhere else teams pick a convention and enforce it with the IDE0007 and IDE0008 style rules.
  • Why did `var f = () => 42;` fail in older C#, and does every method group work now?
    Before C# 10 a lambda had no type of its own, only a conversion to a delegate type the target supplied, so `var` had nothing to infer. C# 10 gave lambdas and single-method method groups a natural type, here `Func<int>`. A method group with several overloads, such as `Console.WriteLine` or `int.Parse`, still has no single natural type and fails with CS8917.

  • var makes the local dynamic, so its type can change later
  • var total = 0 can later accumulate decimal amounts
  • A field can use var as long as it has an initializer
  • var x = null is fine and the type is fixed on first assignment
  • var code runs slower because the type is looked up at run time
  • var and object are interchangeable