programming
coding-practices
variable-declaration
var-keyword
code-optimization

Why should I use var instead of a type?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In C#, var does not mean dynamic typing. It means the compiler infers a strong static type from the initializer. Used well, var removes duplication and improves readability without reducing type safety.

What var Is and Is Not

var is compile-time type inference. The inferred type is fixed once compiled, exactly as if you had written the explicit type yourself.

csharp
1var count = 10;                  // int
2var name = "Codemia";           // string
3var prices = new List<decimal>(); // List<decimal>
4
5// Equivalent explicit declarations:
6int count2 = 10;
7string name2 = "Codemia";
8List<decimal> prices2 = new List<decimal>();

You cannot use var without an initializer for local variables, because the compiler needs information to infer the type.

csharp
// var x; // compile-time error
var x = 42; // valid

Why var Often Improves Code

The biggest gain is avoiding repeated type names that add visual noise, especially with long generic types.

csharp
1Dictionary<string, List<(int Id, string Label)>> map =
2    new Dictionary<string, List<(int Id, string Label)>>();
3
4var cleanerMap = new Dictionary<string, List<(int Id, string Label)>>();

In the second line, the right-hand side already communicates the type clearly. Writing it twice does not add useful information.

Another practical benefit appears during refactoring. If a factory method return type changes from List<Order> to IReadOnlyList<Order>, var callers usually need fewer edits.

csharp
var orders = repository.GetRecentOrders();

The declaration adapts automatically while preserving static type checking.

When Explicit Types Are Better

var is not a universal rule. Use explicit types when inference would hide important intent.

csharp
Stream stream = File.OpenRead("data.bin");

This explicit type tells the reader the abstraction level you depend on. If you wrote var, the inferred concrete type could distract from the intended contract.

Explicit types are also useful with numeric literals where the exact type matters for precision and performance decisions.

csharp
decimal taxRate = 0.0825m;

A balanced style many teams adopt is simple:

  • use var when the right side is obvious
  • use explicit type when it improves communication

Example with LINQ and Anonymous Types

var is required for anonymous types, which are common in projections.

csharp
1var users = new[]
2{
3    new { Id = 1, Name = "Ava" },
4    new { Id = 2, Name = "Noah" }
5};
6
7var result = users
8    .Where(u => u.Id > 1)
9    .Select(u => new { u.Name, NameLength = u.Name.Length })
10    .ToList();
11
12foreach (var item in result)
13{
14    Console.WriteLine($"{item.Name} ({item.NameLength})");
15}

This code is strongly typed from end to end. The compiler enforces member names and value types even though declarations use var.

Team Conventions That Scale

Consistency matters more than ideology. Teams that document a small set of var rules usually review code faster and argue less about style. A common guideline is to require explicit types when constructor calls are hidden behind factory methods with ambiguous names. Another guideline is to encourage var in loops and LINQ pipelines where explicit types create visual clutter.

Treat var as a readability decision for the next maintainer. If a declaration is obvious in one glance, inference is often the cleaner option.

Common Pitfalls

  • Treating var as a style badge instead of a readability tool creates polarized code reviews.
  • Using var with unclear initializers like GetData() can hide intent. Consider explicit type in those spots.
  • Confusing var with dynamic leads to incorrect expectations about runtime binding.
  • Mixing inconsistent conventions within one file makes the code harder to scan.
  • Assuming inferred numeric types match business needs can introduce subtle precision bugs.

Summary

  • var in C# is statically typed inference, not dynamic typing.
  • It removes redundant type repetition and can improve maintainability.
  • It is especially useful with long generic types and anonymous types.
  • Explicit types still matter when they communicate abstraction or precision choices.
  • The best practice is context-driven consistency, not an absolute rule.

Course illustration
Course illustration

All Rights Reserved.