Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use var instead of the class name? [duplicate]

Tags:

variables

c#

var

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?

like image 228
Liam McInroy Avatar asked May 13 '12 14:05

Liam McInroy


People also ask

What is the advantage of using var in C#?

The point of var is to allow anonymous types, without it they would not be possible and that is the reason it exists.

When should I use VAR in Java?

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.

Should I use VAR in Dart?

You can use either and it won't make a difference.

Can we use var in C#?

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.


2 Answers

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.

like image 173
David Anderson Avatar answered Oct 12 '22 04:10

David Anderson


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.

like image 28
Omar Avatar answered Oct 12 '22 06:10

Omar