The var
keyword in C#'s main benefit is to enhance readability, not functionality. Technically, the var
keywords allows for some other unlocks (e.g. use of anonymous objects), but that seems to be outside the scope of this question. Every variable declared with the var
keyword has a type. For instance, you'll find that the following code outputs "String".
var myString = "";
Console.Write(myString.GetType().Name);
Furthermore, the code above is equivalent to:
String myString = "";
Console.Write(myString.GetType().Name);
The var
keyword is simply C#'s way of saying "I can figure out the type for myString
from the context, so don't worry about specifying the type."
var myVariable = (MyType)null
or MyType myVariable = null
should work because you are giving the C# compiler context to figure out what type myVariable
should will be.
For more information: