Var
is used to declare the implicitly typed local variable. It finds the type of
the variable at compile time.
A
Var variable must be initializing at the time of declaration.
Valid var statements:
1. var str = "1";
2. var num = 0;
3. string s = "string";
4. var s2 = s;
5. s2 = null;
6. string s3 =
null;
7. var s4 = s3;
At compile time, the above var statements are compiled to
IL, like this:
1. string str = "1";
2. int num = 0;
3. string s2 = s;
4. string s4 = s3;
1. string str = "1";
2. int num = 0;
3. string s2 = s;
4. string s4 = s3;
The compile-time type value of var variable cannot be null
but the runtime value can be null.
1. // invalid var statements
2. var v; //need to initialize
3. var num = null; // can’t be null at compile time
1. // invalid var statements2. var v; //need to initialize3. var num = null; // can’t be null at compile time
Once var variable is initialized its data type became fixed
to the type of the initial data.
1. // invalid var statements
2. var v2 = "str12";
3. v2 = 3; // int value can’t be assign to implicitly type string variable v2
1. // invalid var statements2. var v2 = "str12";3. v2 = 3; // int value can’t be assign to implicitly type string variable v2
No comments:
Post a Comment