In C #3.0, allow us to define variables like this
VaR age = 10;
VaR name = "James ";
VaR time = datetime. now;
VaR books = new string [] {"AA", "BB "};
But that's all. var only allows us to define the C # compiler to deduce the type of variables through context.
VaR X; // error. There is no initialization device to deduce the type.
Var y = {1, 2, 3}; // error. The set initializer is not allowed.
VaR z = NULL; // error. The null type is not allowed.
This is not allowed.
VaR A = 10;
A = "James ";
Let's look at the Il Implementation of the privacy type.
C #2.0
. Method public hidebysig instance void oldvar () cel managed
{
// Code size 8 (0x8)
. Maxstack 1
. Locals Init ([0] string name)
Il_0000: NOP
Il_0001: ldstr "James"
Il_0006: stloc.0
Il_0007: Ret
} // End of method testvar: oldvar
C #3.0
. Method public hidebysig instance void newvar () cel managed
{
// Code size 8 (0x8)
. Maxstack 1
. Locals Init ([0] string name)
Il_0000: NOP
Il_0001: ldstr "James"
Il_0006: stloc.0
Il_0007: Ret
} // End of method testvar: newvar
Exactly the same.
I guess the emergence of VaR actually exists completely in combination with the anonymous type.
VaR A = new {name = "James", age = 25 };
Console. writeline (A. Name );
Console. writeline (A. Age );
There are also many applications in LINQ.
Int [] numbers = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
VaR querylownums =
From num in numbers
Where num <5
Select num;
Foreach (VAR s in querylownums)
{
Console. Write (S. tostring () + "");
}
That is to say, when the object type is anonymous or the object type is unpredictable.
Code such as VAR age = 10; it is better to write less. First, it is type security, and then it causes as few obstacles as possible for code reading.