What is the `var` keyword and when should you use it?

Beginner

Answer

var enables implicit typing where the compiler determines the type from the assigned value. The variable is still strongly typed.
Best Practices:

  • Use when type is obvious from assignment
  • Required for anonymous types
  • Use with LINQ queries for complex return types
  • Avoid when it reduces code readability
var number = 42;           // int
var text = "Hello";        // string
var list = new List<int>(); // List<int>
// Required for anonymous types
var person = new { Name = "John", Age = 30 };