Why use var instead of the class name?

Liam McInroy picture Liam McInroy · May 13, 2012 · Viewed 7.6k times · Source

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?

Answer

David Anderson picture David Anderson · May 13, 2012

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.