In this video
we will try to understand the importance of VAR keyword
when to use it and
when to
NOT?
In C# 3.0 this keyword was introduced
But today
developer use the VAR keyword left and right
they need it or they don't need it they use the VAR keyword
This video will help to visualize or help to decide
when to use the VAR keyword and when not to use it
When we define any datatype in C#, the way we define a datatype we say - int
i = 10
This i becomes an integer datatype
and str becomes a string datatype
This definition is
is decided i.e. integer because we said int
This str is decided as a string because we said string
When we say VAR
x = 10
This VAR keyword looks at the right hand side
then he says this x has to be an integer
Automatically
he has decided
this x
is an integer
If we
make this as a string
automatically
the VAR keyword says now the data is of type string
and he has made it a string
If we define this
as a decimal like 12.23
He made as a double
The VAR keyword
looks at the value
and
during the compile time itself it decides what is datatype
How useful is this? What is the need of this?
If we uses VAR keyword from primitive datatypes, primitive datatypes means for integer, for boolean
for decimal
then the code will not be readable at all
It is very difficult to guess that x is an integer, g is
a double and this t is a boolean
We need to look at the
the data and decide the datatype
This is more clean
When we say int x, double g
boolean t
This is more readable as compare to VAR
When we are using the VAR keyword
for primitive datatypes
it is not worth
When should we use the VAR keyword?
Use the VAR keyword when we cannot guess
what kind of data can come from the right hand side
We are going to put a LINQ expression here
The right hand side is so difficult to guess
We don't know from this right hand side what fields we will get, what kind of data type will get
Use the VAR keyword
We should use the VAR keyword when we have a LINQ expression
when we have an anonymous type at the right hand side
Use
the VAR keyword when we cannot guess from the right hand side what kind of data type
is there
That brings us to the end of this small video
We will not use the VAR keyword
when it is primitive datatype
Will not use the VAR keyword
when we know what kind of datatype formed from the right hand side
We will use the VAR keyword when we do not know
what kind of datatype is coming from the right hand side
In this video we were trying to understand
when to use the VAR keyword
and when should not use the VAR keyword