Type Inference with var
When var makes code cleaner, and why it doesn't make C# dynamically typed.
2 min read
C# lets you skip writing the type explicitly and let the compiler figure it out:
var age = 30; // inferred as int
var name = "Ada"; // inferred as string
var prices = new List<double>(); // inferred as List<double>This is type inference, and it's important to understand what it isn't: var does not make C# dynamically typed. The compiler still determines a single, fixed type at compile time — it just saves you from typing it out. After that line runs, age is an int forever; you can't later assign a string to it any more than you could with an explicit int age = 30;.
var is compile-time sugar, not a runtime feature
var age = 30;
age = "thirty"; // compile error: cannot convert string to intThis fails exactly like it would with int age = 30;. If you're used to JavaScript's var or Python's dynamic typing, this is the key difference to unlearn — C#'s var is purely a convenience for the writer, not a change in how the type system behaves.
When to use it
var shines when the type is already obvious from the right-hand side:
var user = new User("Ada", 30); // obviously a User
var numbers = new List<int> { 1, 2, 3 }; // obviously a List<int>It's less helpful when the right-hand side doesn't make the type clear:
// Avoid: what does GetValue() return? Not obvious from this line alone.
var result = GetValue();
// Prefer: explicit type when it aids readability
int result = GetValue();A reasonable default: use var when the type is redundant to state (it's right there in new SomeType(...)), and use the explicit type when a reader would otherwise have to go find the method signature to know what they're looking at.
var requires initialization
Because the compiler infers the type from the assigned value, var needs a value on the same line:
var x; // compile error: no initializer, so nothing to infer fromYou'll see var used heavily in modern C# codebases, especially with LINQ queries later in this course, where the result types can get long and awkward to spell out by hand.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.