esse quam videri
Revision as of 00:14, 10 August 2019 by Parker (talk | contribs) (Explanation)
Jump to: navigation, search


“Var” is an implicitly typed local variable that can only be declared locally within a method.



Data types such as int, double, float, or string are all considered explicitly-declared variables, as they are assigned a specific type that the computer compiles different. Var, on the other hand, is implicitly-declared, which means that it can only be declared within a method, otherwise you will receive an error (ex. “”). Var can be considered a more general type of variable. int i = 100;// explicitly typed var j = 100; // implicitly typed

 var variables can be used in the following different contexts:

Local variable in a function For loop Foreach loop Using statement As an anonymous type In a LINQ query expression

var cannot be used as a field type at the class level.

Var can be used any time that the initialization of the variable clearly demonstrates what the variable will contain, as we saw above with var j = 100;. This helps make the code legible and allows readers to clearly understand what var is being used for!


static void Main(string args[]) { //declared locally within a method var i=10 //I know here that var is being used like an integer Console.WriteLine("Type of i is {0}",i.GetType().ToString());

var str = "Hello World!!"; //var is being used like a string Console.WriteLine("Type of str is {0}”, tr.GetType().ToString());

var d = 100.50d; //var is being used like a double Console.WriteLine("Type of d is {0}", d.GetType().ToString());

var b = true; //var is being used like a boolean Console.WriteLine("Type of b is {0}", b.GetType().ToString()); }

External Links