Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I am looking to solicit the community's opinion on whether or not it would be advisable to teach junior developers to code with implicit typing (using var) or should I encourage the use of explicit types.

This is not really a question about the advantages or disadvantages of implicit typing. Junior developers (at least the ones that I deal with) tend to develop very long lasting coding habits in their first years as professional developers and I am trying to think through the potential downside of starting a developer off with the implicit typing approach.

Are there specific scenarios that would warrant the advocacy of explicit typing? What about as part of the discipline of TDD?

And on the issue of ReSharper...

@Eben Geer mentioned ReSharper in his answer. Should we keep the default suggestion to use implicit typing in the inspection templates that our junior developers use?

share|improve this question

migrated from stackoverflow.com Dec 15 '11 at 2:05

This question came from our site for professional and enthusiast programmers.

5  
@DJKRAZE: In my opinion that's more of an education issue. Implicit typing can really clean up readability by reducing source density. –  James Michael Hare Dec 14 '11 at 22:12
7  
5  
The direction we decided to give was that if the type was already specified in the expression, (like with a "new" statement, or if there was a cast), then consider using var. If the type is not obviously discernable (maybe when storing the return value of a method), then prefer to specify the type. In all cases, readability rules. –  JMarsch Dec 14 '11 at 23:12
5  
Yes, I definitely agree that they should use implicit or explicit typing... –  Marc Gravell Dec 14 '11 at 23:20
6  
Oh the poor dull children! They same rules that apply to you should apply to them. End of story. Otherwise your preferential treatment of the dumb noobs can be mis-interpreted as something negative. If they are dull, fire them. If they are not, then challenge them in the same way. –  Job Dec 15 '11 at 2:10

14 Answers 14

up vote 108 down vote accepted

There's no easy rule to follow. It comes down to the basic principle:

Code should convey its meaning to the reader in the most effective way possible.

The var keyword is one of the techniques you can use. It makes the code more readable in some cases, but less readable in others.

See these two examples:

Dictionary<string, List<Widget>> theDictionary = new Dictionary<string, List<Widget>>();

or

var theDictionary = new Dictionary<string, List<Widget>>();

In this case, the explicit type adds nothing to the readability of the code. You KNOW what type theDictionary is, and it's unnecessary to state the type twice in the same line.


But how about this:

var imageData = LoadImageDataFromWidget(widget);

or

Stream imageData = LoadImageDataFromWidget(widget);

Here, the second answer is more readable. You don't automatically know what LoadImageDataFromWidget returns, so the explicit typing gives the reader new and relevant information.

share|improve this answer
5  
This is very well stated. I think your answer really gets to the mentoring aspect of this question. –  syneptody Dec 14 '11 at 22:41
3  
I really agree with implicit typing for new objects or basic values and explicit typing for method' returns and things like that. –  ErickPetru Dec 14 '11 at 22:41
4  
@GiddyUpHorsey "hovering the mouse" makes the bad assumption that you are always going to be viewing the code in a suitable IDE - this almost certainly won't be the case for a code review, for a diff (when committing) or otherwise when viewing code in a repository or, for example, via the list of changed files for a build in Teamcity. More, generically, obscuring things tends to be bad (and this is obscuring things). –  Murph Dec 15 '11 at 8:38
5  
Arguably, the real problems with the 'bad' example are the facts that a method with that name a) returns anything at all (when Load is a command) and b) returns a Stream, which isn't by any stretch of the imagination something that could be regarded as 'image data'. –  AakashM Dec 15 '11 at 9:47
4  
In every single example I've seen where var is considered bad, the real problem is poor naming of variables, methods, etc. The great thing about var is that highlights these problems instead of allowing you to sweep them under the rug. –  Kyralessa Dec 19 '11 at 18:18

Using var should be about readability - there is no general rule (always use it vs never use it). As such it is a matter of opinion.

You need to instil the focus on readability into your juniors.

It is worth writing statements twice - implicitly and explicitly and comparing them for readability, then keeping the one that is more readable (however subjective that may be).

share|improve this answer

That is a very broad question, but my answer would be both. The old answer would be explicit, but with companies like Microsoft embracing things like node.js and dynamic objects, it seems like a good thing to have knowledge of both and, perhaps more importantly, when to use each.

share|improve this answer
5  
except var has nothing to do with 'dynamic' –  jeroenh Dec 14 '11 at 22:18
    
@jeroenh: Disagree. In the case of C#, imagine trying to create a dynamic object implicitly. "var test = new ExpandoObject();" would simply fail. So you would have to know WHEN explicit declarations are necessary: "dynamic test = new ExpandoObject();". Make sense? –  Matthew Patrick Cashatt Dec 14 '11 at 22:28
2  
it doesn't really 'fail', it's just not dynamically typed which is my point. var is about implicit (static) typing, dynamic is about dynamic (runtime) typing. The question is only about the difference between explicit and implicit static typing. –  jeroenh Dec 14 '11 at 22:40

It's hard to have a general rule of thumb here, as the usage is often a matter of taste.

The only cases where I might say to explicitly type is when you want to refer to an object by an interface or subclass instead.

For example:

// more readable, but does dao need to be exposed as a SqlProductDao?
var dao = new SqlProductDao(); 

vs

// may have benefits in hiding the implementation
IProductDao dao = new SqlProductDao(); 

I've also seen some people recommend not using implicit typing for numeric types.

For example:

var x = 1;  // we know this is int, but do they?

That said, there are cases where implicit typing is much more easy to read than explicitly typing, as is the case with many complex LINQ queries.

My personal rule is to use implicit typing where possible and especially where it improves readability (by reducing redundancy and source density). But if using implicit typing in a particular instance makes the code harder to understand, it's up for debate.

share|improve this answer

if you do the later.. I would explain that doing something like this

  var lstColumns = new List<string>(); 

  is the same as doing 
  List<string> lstColumns = new List<string>()
share|improve this answer
    
This sort of begs the question if IEnumerable<> should be taught over List<>? –  syneptody Dec 14 '11 at 22:08
    
I agree but if you know how to use List<> you would not need to worry about IEnumerable unless you want to create your own custom Iterator is that fair to say..? –  DJ KRAZE Dec 14 '11 at 22:11

My personal feeling is it's what comes after the var keyword that matters more. Anybody can look to the right of that statement and either through intellisense or through the declaration understand what the object is, but I think the name of the var matters more to me.

share|improve this answer

Depends. I'd say use explicit typing as a general rule of thumb, simply because it can make code a lot clearer. Plus, you may need it explicitly when assigning to a base class or interface:

IEnumerable<string> e = SomeObject.SomeList; // Not really a great example since List<T> doesn't hide anything from IEnumerable<T>, but oh well.

as opposed to doing the ugly (IMHO):

var e = (IEnumerable<string>)SomeObject.SomeList; // Also a lot longer.

Then there's the matter of compatibility - explicit typing can be used in older versions of C#. So I would say, use explicit typing, except when implicit typing is much more convenient or is necessary.

share|improve this answer
1  
Wrong! You can write var e = (IEnumerable<string>)new List<string>();. Same result with shorter and cleaner code. –  GiddyUpHorsey Dec 15 '11 at 0:53
    
@GiddyUpHorsey: I didn't mean it exactly like that. Obviously, you would actually use var in that case. But if you're retrieving it from a property, then you could cast it, but that is a lot uglier. Updated example, you're right, it's a bad one. –  minitech Dec 15 '11 at 1:48
1  
@GiddyUpHorsey, IEnumerable<string> e = new List<string>(); is better than var+cast in every way, the main advantage being safety: with cast you have to always be vigilant about whether your cast can fail. In case of explicit variable typing the compiler ensures that the cast can't fail. –  Rotsor Dec 15 '11 at 2:29
    
@Rotsor - I don't disagree. However, you have read my comment out of context. My comment was in response to minitech's initial post where he asserted that it was not possible to use var to assign a different type to an expression, i.e. List<string> to IEnumerable<string>. I was simply showing that it is possible. He's changed his answer so it doesn't really matter anymore... –  GiddyUpHorsey Dec 15 '11 at 3:06
1  
Pardon my C# naivete, but why do you even need the case in the second example? Can't you assign any expression to a var-declared variable? –  David Harkness Dec 15 '11 at 8:44

Implicit typing in C# was created to support the projection of data into new anonymous types in LINQ queries. However, many developers use it to save typing or to improve readability. The more important thing would be to teach your junior developers to use ReSharper which will make explicit typing much easier to type (on the keyboard) than implicit typing.

UPDATE

The following article gives a good breakdown about the relation between var, the compiler, and LINQ:

Albahari: LINQ Myth #1

share|improve this answer
    
Can you give an example just when the type is not known at compile time? I can't think of one. –  aevitas Dec 14 '11 at 23:21
1  
agree, this is nonsense. .net is strongly typed. –  Myles McDonnell Dec 14 '11 at 23:30
    
What I said was wrong. I've clarified my answer. –  Eben Geer Dec 15 '11 at 0:22

I don't think you should encourage them to do either, unless you've implemented a coding standard (which to me would be a counter-productive one anyway).

Encourage them to use using, and interfaces, doc comments, and IDispose etc. Things that will make a real difference.

As far as I'm concerned aside from where you have to use var, this has about as much value as an indenting style.

share|improve this answer

Personally I do a mixture of both. When I'm declaring fields on a local scope I do

StringBuilder sb = new StringBuilder();

For example, so the type is explicitly specified for readability. However, when I'm iterating over a collection, like so:

List<object> Objects = new List<object>();

foreach (var o in Objects)
{
    // Do something
}

Since, by looking at the collection it is iterating over, I can already make out the type quite easily, thus I find it superfluous to explicitly define the type in the loop itself.

I mostly apply this only when I'm working on projects other people will have to work with as well, so they don't have to second guess themselves which types they are working with, instead it's all there for them. When I'm developing projects I will only work on myself, I follow ReSharper's advice and always use var.

As for the question, I think explicit typing would be better practice. Especially if they're new to the language or programming in general, it gives the readability of the code a big boost.

share|improve this answer
2  
But by naming the same type twice, you cause the reader to waste a small bit of time and energy to compare the two types to see if they are identical. Seeing var is a good, quick indicator that the reader either doesn't need to know or should look no further than the other side of the assignment operator. –  David Harkness Dec 15 '11 at 8:39

If the junior developers are not familiar with the concept of explicit versus implicit typing, I would suggest encouraging explicit typing. Once that falls into the category of rote knowledge, I would introduce implicit typing and explain the different camps of thought and possible advantages and disadvantages of the practice.

I mean, fundamentally, "var" is a syntactic shortcut, and I think that it's better, in general, for people who are learning first to learn the "standard" way and then to learn shortcuts. I'd encourage "learn and master explicit first and then learn this shortcut once your discretion can be trusted" for this in the same way that I'd encourage learning basic HTML before using a designer or learning the fundamentals of databases and querying before using an ORM. I prefer that people taking shortcuts know what they're 'shortcutting' whenever possible and practical.

share|improve this answer
    
Great answer! Fundamentals First everything Next! –  Karthik Sreenivasan Jan 20 '12 at 12:09

Using an untyped language (PHP) for most recent projects, I can say that choosing meaningful method names goes a long way. Specifying the type of the variable requires more work when refactoring than changing the name of a method. A name like LoadImageFromFileAsStream can tell you everything you need to know and shield you from having to track down the type declarations when you change it to LoadImageFromFileAsByteArray.

share|improve this answer

I find Eric Lipperts post on the subject to be highly informative; I would even say ' authorative' :

http://blogs.msdn.com/b/ericlippert/archive/2011/04/20/uses-and-misuses-of-implicit-typing.aspx

Here's the summary, repeated verbatim:

  • Use var when you have to; when you are using anonymous types.
  • Use var when the type of the declaration is obvious from the initializer, especially if it is an object creation. This eliminates redundancy.
  • Consider using var if the code emphasizes the semantic "business purpose" of the variable and downplays the "mechanical" details of its storage.
  • Use explicit types if doing so is necessary for the code to be correctly understood and maintained.
  • Use descriptive variable names regardless of whether you use "var". Variable names should represent the semantics of the variable, not details of its storage; "decimalRate" is bad; "interestRate" is good.
share|improve this answer
    
Thanks for the link. Very useful! –  Karthik Sreenivasan Jan 20 '12 at 12:01

Good naming also solves a lot. Let's take Andrews example:

var imageData = LoadImageDataFromWidget(widget);

With better naming:

var imageStream = LoadImageStreamFromWidget(widget);

With the better name, suddenly the var is also very readable. Just don't use var for primitives like string, int,...

share|improve this answer
    
I do this by giving the method a good name. That way you won't need to change the name of every variable when refactoring the method. –  David Harkness Dec 15 '11 at 8:40
    
So what happens when you decide that you using a stream for an image was the wrong approach and you change the Load method signature? (This may not apply in the specific case but it is certainly a generic problem.) –  Murph Dec 15 '11 at 8:41
    
Well, as David says, picking a better name for the load method can fix it, "LoadImageStreamFromWidget". –  Carra Dec 15 '11 at 8:50

Your Answer

 
discard

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.