After declaring an object of implicit type with var
keyword, is it possible to use the members, methods or properties specific to the type that has been assigned to it by compiler in any further statements?
Using members of Var type
93 views Asked by salil87 At
2
There are 2 answers
0
On
If you use var
, the you have to immediately initialize the variable. Example:
var a = 1;
This tells the compiler it's an int. But if you don't initialize, then the compiler doesn't know what type it should be using.
var b;
What type is b
?
The same applies for members of classes.
var
is just a convenience feature so you don't have to type in the name of the class or the fully qualified namespace.
Yes, absolute - because
var
isn't actually a type. It just tells the compiler: "I'm not going to explicitly tell you the type - just use the compile-time type of the right-hand operand of the assignment operator to work out what type the variable is."So for example:
As well as being convenient,
var
was introduced to enable anonymous types, where you couldn't declare the variable type explicitly. For example:Compare this with
dynamic
, where the compiler basically defers any use of members until execution-time, to bind them based on the execution-time type: