Possible Duplicate:
What's the point of the var keyword?
What advantages does using var have over the explicit type in C#?
I always see other people producing code like:
var smtp = new SmtpClient();
But why use var
instead of SmtpClient
in this case? I ALWAYS use
SmtpClient smtp = new SmtpClient();
Is var
more efficient? Why use var
instead of the actual variable type? Am I missing something?
The point of var is to allow anonymous types, without it they would not be possible and that is the reason it exists.
In Java, var can be used only where type inference is desired; it cannot be used where a type is declared explicitly. If val were added, it too could be used only where type inference is used. The use of var or val in Java could not be used to control immutability if the type were declared explicitly.
You can use either and it won't make a difference.
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. var cannot be used on fields at class scope. Variables declared by using var cannot be used in the initialization expression.
Imagine this.
Dictionary<Dictionary<String, String>, String> items = new Dictionary<Dictionary<String, String>, String>();
var
is useful for things like that.
var items = new Dictionary<Dictionary<String, String>, String>();
Much simpler. The point of var
is the same as auto
in C++ 11, the compiler knows the type so why must we repeat ourselves so much. I personally use var
rarely, but only for lengthly declarations. It's just syntactic sugar.
No it isn't more efficient. It's the same thing of write explicitly the type. Infact it is good programming write the type of the variable instead of use var
because it makes the code more readable.
So:
var smtp = new SmtpClient();
And:
SmtpClient smtp = new SmtpClient();
Are the same thing wrote in two different ways.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With