The var keyword instructs the compiler
to infer the type of the variable from the expression on the right side of the
initialization statement. The inferred type may be a built-in type, an
anonymous type, a user-defined type.
E.g.
ways in which local variables can be declared with var
var a = 1; // a is compiled as
int
var b = "Narendra"; // b is compiled as string
var c = new List<int>(); // c is compiled as
List<int>
var d = new { Name = "Naren", Age = 27 }; // d is
compiled as an anonymous type
It is important to understand that
the var keyword does not mean "variant" and does not
indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the
most appropriate type.
E.g. var myVariable = 1; // myVariable is compiled as int
If I try to
assign it differnt value than int as :
myVariable = "some string"; then it will throw
error as " Error: Cannot implicitly convert type
'string' to 'int' "
Following
restrictions apply to implicitly-typed variable declarations:
·
var can
only be used when a local variable is declared and initialized in the same statement;
the variable cannot be initialized to
null, or to a method group or an anonymous function.
NOTE: The compile-time type value of var
variable cannot be null but the runtime value can be null.
E.g.
If we try var a = null; It throws error "
Error: Cannot assign <null> to an implicitly-typed local variable."
But following is
valid statement
string s=null;
var a = s;
·
var cannot be used on fields at class
scope.
·
Multiple
implicitly-typed variables cannot be initialized in the same statement.
E.g. var param1 = 1, param2
= 2; --> This is not allowed. This
will throw compilation error "Error: Implicitly-typed local variables
cannot have multiple declarators"
Following is valid declaration.
var param1 = 1;
var param2 = 2;
No comments:
Post a Comment