var keyword in C#-Restrictions and Advantage of using var variable

In this article, we will understand the var keyword in C#.

var keyword in C#

The  var  keyword was introduced in C# 3.0 to declare an implicitly typed of local variable to hold any type of data.
In implicitly typed variables, the type of the variable declared is decided by the compiler at the compile-time based on the type of the value that the variable is initialized with.
The variable declared as var is mandatory to initialize at the time of declaration.

In simple words, the var keyword in C# is used to declare a variable whose type is not pre-decided.
By using “var”, we are supposed to give full control to the C# compiler to determine the data type of the local variable.

var keyword in C#
var variable in C#

In the above image, we can see that the visual studio shows the intelligence because the type of variable assigned is known to the compiler at the compile time.

The following are the implicitly and explicitly typed variables declaration in C#.

Continue reading “var keyword in C#-Restrictions and Advantage of using var variable”