Yes, the var
keyword is only allowed for local variables.
It was introduced in the language to be able to handle an anonymous type, that only exists in a local scope. As the anonymous type is limited to the local scope, it makes sense to only allow the var
keyword in a local scope.
Additionally, it never works to use the var
keyword without specifying a value, as that is used to infer the data type:
var x = "asdf"; // works
var x; // doesn't work
The normal way of declaring a variable is using a specific data type. Use the var
keyword when you can't specify a data type (e.g. when the type is anonymjous) or when the type is superflous (e.g. repeated literally in the value). Example:
var x = new { Key = 42, Name = "asdf" };
var y = new System.Text.StringBuilder();