What is var keyword in C#: Simple Explanation and Example
var keyword lets the compiler automatically figure out the type of a variable based on the value you assign to it. It is a way to write cleaner code without explicitly stating the variable's type, but the type is still fixed once set.How It Works
Think of var as a smart assistant that looks at the value you give it and decides the type for you. For example, if you write var number = 5;, the assistant sees the number 5 and knows the type is int. This means you don't have to write int number = 5; explicitly.
However, once the assistant picks the type, it sticks with it. You cannot change the type later. So, var is not a way to make a variable flexible; it just saves you from typing the type name when it is obvious.
This helps keep your code neat and easier to read, especially when the type is long or complex.
Example
This example shows how var automatically sets the variable type based on the assigned value.
using System; class Program { static void Main() { var message = "Hello, world!"; // compiler sets type as string var count = 10; // compiler sets type as int var price = 9.99; // compiler sets type as double Console.WriteLine(message); Console.WriteLine(count); Console.WriteLine(price); } }
When to Use
Use var when the type is obvious from the value, which makes your code shorter and cleaner. For example, when creating new objects or working with LINQ queries, var helps avoid repeating long type names.
However, avoid var if it makes the code unclear or confusing, especially when the type is not obvious. Clear code is more important than saving a few keystrokes.
Real-world use cases include declaring collections, anonymous types, or when the exact type is complex but clear from the right side of the assignment.
Key Points
varlets the compiler infer the variable type from the assigned value.- The variable type is fixed and cannot change after assignment.
- It improves code readability when the type is obvious or complex.
- Avoid
varif it makes the code harder to understand.
Key Takeaways
var automatically infers the variable type from the assigned value.var to write cleaner code when the type is obvious.var if it reduces code clarity.