Why use var instead of a class name?

Possible duplicate:
What is the meaning of the var keyword?
What are the benefits of using var in an 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? Did I miss something?

+7
source share
4 answers

Imagine this.

 Dictionary<Dictionary<String, String>, String> items = new Dictionary<Dictionary<String, String>, String>(); 

var is useful for such things.

 var items = new Dictionary<Dictionary<String, String>, String>(); 

Much easier. The var point is the same as auto in C ++ 11, the compiler knows the type, so why should we repeat ourselves so much. I rarely use var rarely, but only for long declarations. It is just syntactic sugar.

+16
source

No, this is not about efficiency, but only about the style of writing code.

Given that this is about style, this rule cannot always be applied.

Immunity after snipplet:

var myVar = Some3dPartFunction() , what is the type of myVar ? This is not entirely clear, and not good, in terms of code, to write in this way.

In short, choose the right entry in a smart way.

+15
source

Syntactic sugar:

 var smtp = new SmtpClient(); 

equally:

 SmtpClient smtp = new SmtpClient(); 

This is a new feature in C # 3.0 called type inference.

+1
source

No, it is not more effective. This is the same as the explicit record type. Infact is good programming, write a variable type instead of using var , because it makes the code more readable.

So:

 var smtp = new SmtpClient(); 

and

 SmtpClient smtp = new SmtpClient(); 

The same is written in two different ways.

+1
source

All Articles