C# 3.0 introduced Var type to declare implicitly typed local variable. An implicitly typed local variable is a strongly typed variable without explicit type declaration.
The compiler looks at the type of expression on the right side of the assignment operator (=) and derives the type during compilation.
For example : Lets look at below code
1 |
var i = 123 //Implicitly typed. |
In above, we have declared i using Var keyword without any type specified, which is known as implicitly typed variable. Here compiler determines the type information during compilation.
However in below code example. we have declared variable int a with explicitly type information, this is known as explicitly typed variable.
1 |
int a = 1234 //Explicitly typed. |
Syntax & Usage of Var type :
Following are some sample code demonstrating the use of this feature.
1 2 |
var i = 12345; Console.WriteLine(i.GetType()); //Prints System.Int32 |
The compiler looks at the type of expression on the right side of the assignment operator (=). Here 12345 is of type System.Int32 , hence compiler derives the variable i of type System.Int32.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; namespace VarType { class Program { static void Main(string[] args) { var arrNum = new Int32[] { 12, 25, 35 }; Console.WriteLine("Type of arrNum : {0} " , arrNum.GetType()); //Prints System.Int32[] var arrString = new String[] { "Apple", "Mango", "Papaya" }; Console.WriteLine("Type of arrString : {0} ", arrString.GetType()); //Prints System.String[] } } } |
In the first sample code above, compiler derives the type of var aarNum to be of System.Int32[] by looking at the right side expression. Similarly in the second example it derives the type of var arrString variable to be of System.String[].
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System; using System.Collections.Generic; namespace VarTypeDemo { class Program { static void Main(string[] args) { var employee = new Dictionary<int, string>() { [1] = "George", [2] = "Diego" }; Console.WriteLine(employee.GetType()); //Prints System.Collections.Generic.Dictionary`2[System.Int32,System.String] foreach (var item in employee) Console.WriteLine(item.GetType()); //Prints System.Collections.Generic.KeyValuePair`2[System.Int32,System.String] } } } |
In the first assignment, compiler derives var employee to be Generic.Dictionary`2[System.Int32,System.String] and in the for each loop also, compiler automatically derives the type of element present in the dictionary.
In the above code sample, we see code simplicity of implicitly typed local variable feature, without this feature, we would have to specify Dictionary<int, string> on the both sides of the assignment operator.
Also if we change the generic type then no need to change on the both side. Only make the change the type on the right side and that will work.
Declaring a local variable using Var is just a syntactical shortcut. It allows the compiler to derive specific data type from an expression.
Use of Var in Anonymous Type :
Anonymous type in C# allows to declare type without any name. When you initialize a variable with an anonymous type, then you must declare the variable as Var . This will allow you to access the properties of the object later.
1 2 |
var employee = new { FirstName = "Amit", MiddleName = "Kumar", LastName = "Rathod" }; Console.WriteLine("First Name : {0} Middle Name : {1} Last Name : {2}", employee.FirstName, employee.MiddleName, employee.LastName); |
OutPut:
In the above example var employee is an anonymous type, here we have used the Var keyword which allows the compiler to derive the object property types at compile time.
Key Points :
Following are some of the key points, while using Var.
i ) – You must explicitly initialize a variable declared as Var type, here in below example var i will throw compile error.
1 2 |
var i ; // Throws an error var x = 10 // Works fine |
ii ) – You cannot assign null to a Var type, below line will throw compile time error.
1 |
var z = null // Cannot assign a null to an implicitly type variable error |
iii ) – You must declare Var as a local variable scope inside a method. Declaring Var as field level scope inside a class throws error. In below example var FirstName = "" throws an error as it is in field level scope. However var fullName = "Amit kumar" doesn’t have any issue as it is in local variable scope.
1 2 3 4 5 6 7 8 9 |
class employee { var FirstName= "" //Compile error public string GetFullName() { var fullName = "Amit kumar";//Local variable, no error return fullName; } } |
iv ) – You cannot initialize multiple implicitly-typed variables in the same statement, below line will give compile time error.
1 |
var i = 1, j = 10, k = 11; // Compile time error, as it is not allowed |
v ) – You cannot assign an anonymous method to Var, below anonymous method assignment will throw compile time error.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
namespace VarTypeDemo { class Program { static void Main(string[] args) { //Compile time error. var checkString = delegate (string value) { return string.IsNullOrEmpty(value); }; } } } |
However, below anonymous method assignment works fine.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
namespace VarTypeDemo { class Program { static void Main(string[] args) { Func<string, bool> checkString = delegate (string value) { return string.IsNullOrEmpty(value); }; bool b = checkString("me"); } } } |
Var and Dynamic type sounds similar but there are a lot difference between them . If you would like to explore on Dynamic type then you can do it here.
Thanks for your time 🙂 feel free to provide your feedback and do check my other blogs on Dynamic type in C# , Nullable type in C# , Anonymous type in C# and Reference Type and Value type .