Declaring local variables implicitly has some restrictions; the variable must be initialized to some expression that can not be null.
var a= 10;
var z = "Rekha";
The primary reason for its existence is the introduction of anonymous types in C#
Another point to stress is that variable inference does not work for class level fields or method arguments or anywhere else other than for local variables in a method.
Advantages :
Less typing with no loss of functionality
Increases the type safety of your code. A foreach loop using an iteration variable which is typed to var will catch silently casts that are introduced with explicit types
Makes it so you don't have to write the same name twice in a variable declaration.
Some features, such as declaring a strongly typed anonymous type local variable, require the use of var
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment