Seva Seva - 1 month ago 7
C# Question

What does "var" mean in C#?

In C#, how does keyword "var" work?

Answer

It means that the type of the local being declared will be inferred by the compiler:

// This statement:
var foo = "bar";
// Is equivalent to this statement:
string foo = "bar";

Notably, var does not define a variable to be of a dynamic type. So this is NOT legal:

var foo = "bar";
foo = 1; // Compiler error, the foo variable holds strings, not ints

var has only two uses:

  1. It requires less typing to declare variables, especially when declaring a variable as a nested generic type.
  2. It must be used when storing a reference to an object of an anonymous type, because the type name cannot be known in advance: var foo = new { Bar = "bar" };

You cannot use var as the type of anything but locals. So you can't use the keyword var to declare field/property/parameter/return types.