Question

Are there any best practices when declaring variable with respect to the use of var versus the actual type?

What I have seen so far is that complex types and reference types are usually declared with var:

So, instead of

List<int> list = new List<int>();

this seem to be preferred

var list = new List<int>();

But what about value types? What is preferred?

This?

int i = 0;
decimal interest = 0m;

or this

var i = 0;
var interest = 0m;

Finally, what about strings? They are reference types but frequently string is used.

So, this?

string name = "Joe";

or this

var name = "Joe";

Thanks.

1 Answers

Personally, I almost exclusively prefer var, since:

  1. Generally speaking, it's pretty obvious what the type will be based on the right-hand-side of the assignment.
  2. It's more immune to refactorings - ie if you update a method to return List<int> instead of int[], odds are you're just looping through the thing anyway so it doesn't really matter what kind of enumerable it is, so long as you can still loop through it. With var, you don't need to update any calling code.

Pretty much the only times I find myself not using var is when there's no alternative, ie declaring a variable without initializing it, or else if I want to have a variable of a less derived type than what would normally be inferred for whatever reason (happens, but rarely).

Also, don't forget, the inferred type is but an f12 keystroke away (or even just mousing over it will reveal the inferred type), so even if #1 doesn't hold up, it's not hard to see what it is.