What is the use of Var Keyword in c#
Var keyword is an implicit way of defining data type. C# 3.0 adds the interesting behavior of Declaring Local Variables Implicitly. In simple word var keyword look the data in right hand side then create appropriate data type.
var keyword define data type statically in compile time not on runtime.The primary reason for its existence is the introduction of anonymous types in C#
When you define below variable in C#:
int i=0 ;
This is called explicit declaration or you can say direct declaration.
Because you are actually define that which data type you want to declare. This is most common way that how we define variable in C#.
But when we define variable as var type like
This is called implicit or you can say indirect declaration.
int i=0; >> Explict [direct]
var i=0; >> Implicit [indirect]
When you define var data type then compiler look data which is in right hand side then create appropriate data type. In above code when we assign 0 then compiler in during generation IL code statically defined integer type.
So, we can say that var keyword is not like object type which point any data type at run time.
Finally we can say “ var keyword is an implicit way of defining data type. In simple word var keyword look the data in right hand side then create appropriate data type.”
var keyword define data type statically & not on runtime.
var num=124; >> we define variable num as var type and assign interger value
num="abc"; >> now we try to assign string in num.
After this when we compile this code we get compilation error.
"Cannot implicitly convert type 'string' to 'int'.
This prove that var type define data in compile type not run time.
- Less typing with no loss of functionality
- Some features, such as declaring a strongly typed anonymous type local variable, require the use of var
- Increases the type safety of your code