Alex Rivera | Logout

Should I *always* favour implictly typed local variables in C# 3.0?

Asked 2008-08-19T21:49:07.347
29

Resharper certainly thinks so, and out of the box it will nag you to convert

Dooberry dooberry = new Dooberry();

to

var dooberry = new Dooberry();

Is that really considered the best style?

Edit
Report

4 Answers

4

@jongalloway - var doesn't necessarily make your code more unreadable.

var myvariable = DateTime.Now
DateTime myvariable = DateTime.Now;

The first is just as readable as the second and requires less work

var myvariable = ResultFromMethod();

here, you have a point, var could make the code less readable. I like var because if I change a decimal to a double, I don't have to go change it in a bunch of places (and don't say refactor, sometimes I forget, just let me var!)

EDIT: just read the article, I agree. lol.

answered 2008-08-19T22:26:44.447
2

There was a good discussion on this @ Coding Horror

Personally I try to keep its use to a minimum, I have found it hurts readability especially when assigning a variable from a method call.

answered 2008-08-19T21:55:23.620
0

"Best style" is subjective and varies depending on context.

Sometimes it is way easier to use 'var' instead of typing out some hugely long class name, or if you're unsure of the return type of a given function. I find I use 'var' more when mucking about with Linq, or in for loop declarations.

Other times, using the full class name is more helpful as it documents the code better than 'var' does.

I feel that it's up to the developer to make the decision. There is no silver bullet. No "one true way".

Cheers!

answered 2008-08-19T21:54:30.813
0

There's a really good MSDN article on this topic and it outlines some cases where you can't use var:

The following restrictions apply to implicitly-typed variable declarations:

  • 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. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);
  • Multiple implicitly-typed variables cannot be initialized in the same statement.
  • If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.

I would recommend checking it out to understand the full implications of using var in your code.

answered 2008-08-20T01:53:58.333

Your Answer