Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
MyDbEntities context = new MyDbEntities();
var result = context.StoredProcedureName(userId);

In the situation above, is it considered best practice to use var or ObjectResult<ComplexType>?

share|improve this question
I use the term dynamically bind loosely, I know its a compile time occurance. – P.Brian.Mackey Mar 7 '12 at 22:46
up vote 5 down vote accepted

Generally, if you can't tell the return type by reading the line in question (or another, very nearby line), you should use the explicit type. This will make the readability of your code much better.

var should be used only when the implicit type is discoverable in the same line of code or very nearby.

In your example, you should really use ObjectResult<ComplexType>:

ObjectResult<ComplexType> result = context.StoredProcedureName(userId);

These cases are ok for var, because the types are easily discernible:

var user = context.Users.First(x => x.Id == userId);


var users = context.Users.Where(x => x.LastName == lastName);
foreach(var user in users)
  //do stuff
share|improve this answer

I would have no problem using var if your method name and/or variable name clearly indicated what was being returned. Readability is the key.

var foos = context.GetUnallocatedFoosForUser(userId);

For what it's worth, when you use var, you're not dynamically binding anything. The compiler AND the IDE know what type (even if it's just object) that you're dealing with here. The var keyword is just a short-hand for "use whatever type is on the right hand side."

It would be different if you used dynamic, but that's a very different kind of question and not really applicable in this situation.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.