The var keyword in C# is used for local variable type inference. It allows the compiler to determine the variable type from the value assigned on the right side. This can make code shorter and cleaner when the type is obvious, but it can also make code harder to read if used carelessly.
A common beginner misunderstanding is that var makes C# dynamically typed. It does not. C# remains strongly typed. The compiler still decides one fixed type for the variable at compile time. After that, the variable cannot suddenly store a value of a different type.
What Is var in C#?
var is a contextual keyword used to declare local variables when the compiler can infer the type from the initializer.
var number = 10;
var name = "Alex";
var active = true;
In this example, number becomes an int, name becomes a string, and active becomes a bool. The types are not unknown; they are inferred by the compiler.
varhides the type in source code, but it does not remove the type from the program.
Basic Syntax of var
var variableName = value;
The initializer is required. You cannot declare a var variable without assigning a value because the compiler would not know what type to infer.
// var value; // Error
var Is Still Strongly Typed
Once the compiler infers a type, the variable keeps that type.
var score = 90;
// score = "high"; // Error
The variable score is inferred as int. Assigning a string later is invalid because the type has already been decided.
var vs Explicit Type
Both declarations below produce an integer variable.
int count = 5;
var total = 10;
The difference is readability. Explicit typing shows the type directly. var asks the reader to infer the type from the initializer.
| Style | Example | Best When |
|---|---|---|
| Explicit type | Customer customer = ... | The type improves readability. |
var | var customer = new Customer(); | The type is obvious from the right side. |
Good Uses of var
var works well when the type is obvious from the assignment.
var user = new User();
var numbers = new List<int>();
var createdAt = DateTime.Now;
In these examples, the right side clearly communicates the type, so var avoids repetition without hiding important information.
Bad Uses of var
var becomes less helpful when the right side does not make the type clear.
var result = GetData();
If GetData() does not clearly reveal the return type, the reader may need to jump to another method definition. In that case, an explicit type may be more readable.
var with Anonymous Types
var is required when working with anonymous types because anonymous types do not have a named type you can write directly.
var student = new
{
Name = "Riya",
Marks = 95
};
Console.WriteLine(student.Name);
The compiler creates an anonymous type behind the scenes. Since the type has no explicit name in your code, var is the natural choice.
var with LINQ
var is commonly used with LINQ queries because query results can have complex generic types or anonymous projections.
var highScores = scores.Where(score => score > 80);
The exact type may be long, but the intent is readable from the variable name and query expression.
Where var Cannot Be Used
- You cannot use
varfor fields. - You cannot use
varfor method parameters. - You cannot use
varfor method return types. - You cannot declare
varwithout an initializer. - You cannot initialize
varwithnullalone.
// var name = null; // Error
The compiler cannot infer a useful type from null alone.
var vs dynamic
var and dynamic are very different. var is resolved at compile time. dynamic delays type checking until runtime.
| Keyword | Type Decided | Type Safety |
|---|---|---|
var | Compile time | Strongly typed |
dynamic | Runtime | Runtime checked |
Use var for cleaner local declarations. Do not use dynamic as a replacement for var.
Inferred Numeric Types
When var is used with numeric literals, the compiler chooses the type based on the literal. This is why suffixes still matter even when the left side uses var.
var a = 10; // int
var b = 10L; // long
var c = 10.5; // double
var d = 10.5m; // decimal
var e = 10.5f; // float
The keyword var does not remove the need to understand data types. It only lets the compiler write the type for you internally.
var in foreach Loops
var is commonly used in foreach loops because the element type is usually clear from the collection.
List<string> names = new List<string> { "Aman", "Riya", "Neha" };
foreach (var name in names)
{
Console.WriteLine(name);
}
Here, name is inferred as string. The code remains readable because names clearly suggests a string collection.
var and Target-Typed new
Modern C# also supports target-typed new, which is almost the opposite of var. With var, the type appears on the right side. With target-typed new, the type appears on the left side.
var list1 = new List<int>();
List<int> list2 = new();
Both can be readable when used well. The main rule is to avoid hiding the type from both sides at once.
Readability Examples
This use of var is readable because the type is obvious:
var customer = new Customer();
This use is weaker because the type is hidden behind a vague method name:
var data = Load();
If the method name and variable name do not reveal enough meaning, an explicit type can make the code easier to understand.
Team Style and Consistency
Different C# teams follow different style rules for var. Some teams prefer var whenever possible. Others prefer explicit types except for anonymous types and obvious object creation. The important thing is consistency. A codebase is easier to read when the team follows one clear convention instead of mixing styles randomly.
What the Compiler Actually Does
When the compiler sees a var declaration, it examines the initializer and replaces the idea of var with the actual inferred type. The compiled program does not carry a special dynamic var type. It carries the real type selected during compilation.
This means there is no runtime performance cost just because you used var. The main tradeoff is readability in the source code, not execution speed.
IDE Support for var
Modern C# editors can show the inferred type when you hover over a var variable. This helps while coding, but source code should still be readable during reviews, diffs, and documentation. Not every reader will hover over every variable, so names and context still matter.
var and Refactoring
var can make some refactoring easier because the left side does not need to change when the right-side type changes. However, that can also hide important type changes from readers. If changing the type affects behavior, readability should win over shorter syntax.
Anonymous Type Use Case
Anonymous types are commonly used when selecting only a few fields from a larger object, especially in LINQ queries or temporary projections.
var summary = new
{
ProductName = "Mouse",
Price = 499,
InStock = true
};
There is no explicit class name to write for summary, so var is required. This is one of the strongest legitimate uses of var.
Beginner Code vs Professional Code
For beginners, explicit types are often useful because they reinforce learning. Seeing int, string, bool, and List<int> repeatedly helps build type awareness. In professional code, var is often used more frequently when the team already understands the type system and wants cleaner declarations.
That does not mean professionals should always use var. Clear code depends on context. If the variable name and initializer make the type obvious, var is usually fine. If the type carries important meaning, writing it explicitly can make the code easier to review.
A Practical Rule for var
Before using var, ask one question: can a reader understand the type and purpose without opening another file or hovering in the IDE? If yes, var is probably fine. If no, prefer an explicit type or improve the variable and method names.
var with Nullable Values
When nullable reference types are enabled, var can still infer nullable-aware types from expressions. However, the nullability may not be obvious just by looking at the keyword. If null handling is important for readability, an explicit nullable type such as string? may communicate intent better than var.
Common Mistakes with var in C#
- Thinking
varmeans dynamically typed. - Using
varwhen the type is not obvious. - Trying to declare
varwithout assigning a value. - Trying to use
varas a field type. - Using vague variable names with
var. - Confusing
varwithobjectordynamic.
Is var dynamic in C#?
No. var is compile-time type inference. The variable still has one fixed strong type.
Can I use var without assigning a value?
No. The compiler needs an initializer to infer the variable type.
Should beginners use var?
Beginners should first understand explicit types clearly. After that, use var when the type is obvious and readability improves.
Best Practices for var in C#
- Use
varwhen the type is obvious from the right side. - Use explicit types when they improve readability.
- Use meaningful variable names.
- Use
varnaturally with anonymous types and LINQ. - Avoid
varwhen it hides important information. - Do not confuse
varwithdynamic.
The var keyword in C# is a readability tool, not a dynamic typing feature. Used well, it removes repetition and keeps code clean. Used poorly, it hides useful information. The right choice depends on whether the inferred type is clear to the human reader.