What is var in C#?

Answer

var is an implicitly typed local variable keyword. The compiler infers the type from the initialization expression at compile time — it is NOT dynamic typing. var x = 42; is identical to int x = 42;. Once inferred, the type is fixed and cannot change. Best practices: (1) Use var when the type is obvious from context: var list = new List<string>();. (2) Use explicit type when clarity matters: IEnumerable<string> items = GetItems(); — makes the intended type clear. (3) Especially useful with long generic types: var dict = new Dictionary<string, List<UserRole>>();. (4) Required for anonymous types: var person = new { Name = "Alice", Age = 30 }; — no other way to type this. dynamic is very different — it defers all type checking to runtime.