var in C# is not equal to var in JavaScript, etc.
var is syntactic sugar, it is short for variable.
var does not change the functionality of the code it is used in.
var is a visual mask for the real Type.
var is interpreted by the compiler as its real Type.
var
always requires initialization - you can't do 'var myVariable;'
There is no Type to defer from the assignment in the above case, so var is just a mask without a wearer.
You can hover-over the var keyword in Visual Studio to reveal its real Type in a tool-tip, if the Type that is deferred can not be easily assumed by the developer.
var is extremely useful if it is used in code that could be changed a lot, for example;
List<int> values = new List<int>( );
Dictionary<string, int> myDictionary = new Dictionary<string, int>( );
foreach(KeyValuePair<string, int> o in myDictionary)
{
values.Add( o.Value );
}
May be updated to;
List<int> values = new List<int>( );
int[] myDictionary = new int[100];
foreach(int o in myDictionary)
{
values.Add( o );
}
That required quite a few edits,
but if we use var;
var values = new List<int>( );
var myDictionary = new Dictionary<string, int>( 100 );
foreach(var o in myDictionary)
{
values.Add( o.Value );
}
It is
much easier to update the implementation;
var values = new List<int>( );
var myDictionary = new int[100];
foreach(var o in myDictionary)
{
values.Add( o );
}
Basically, we don't have to rewrite every Type declaration for the variables we use, they are automatically interpreted as the Type of the assignment ( the value on the right-hand side of the = )
In summary, var doesn't affect the compiled code, it doesn't affect performance at run-time (when you run the exe).
It reduces file size, increases readability and improves compatibility.
var is encouraged, but not essential; depending on style, a developer may use var explicitly for every declaration, or they may use it for non-standard Types only (built-in Types like byte, int, bool, etc. are left as they are). Or they may use neither.
I personally prefer to use var for everything, simply because I write a high volume of code that is ever-changing; if I had to manually replace the Typed variable declarations every time I updated the return Type of a method (or whatever), then VNc would be on a much longer development cycle.
---------
C# is a strongly-typed language.
var usually appears in loosely-typed languages such as JavaScript, where var can be mutated and assigned any Type.
C# does however have an object Type that allows a pseudo-loosely-typed object to be created; the 'dynamic' (DynamicObject) type.
It is rarely used, but worth looking in to if you want to write C# without knowing what members your Type will have. (Ex; parsing Json in to a dynamic object where properties of that object may or may not exist).