So yesterday I and my friend were discussing the var keyword over some Minecraft gameplay and it seemed we had two very different opinions on when to use the keyword. We’re both hobby-programmers studying computer science so we’re no experts by any means, but I would like some input or opinions from more experienced developers in order to maybe improve my own skillset.

My take on var is that I use it as a replacement for the type name when it is either clear what the type really is or the type name is very long. I always thought of it as an option to balance length and readability but that’s just my opinion.

Instead of Dictionary<int, List<CustomClass[]>> dic = new Dictionary<int, List<CustomClass[]>>(); I would write var dic = new Dictionary<int, List<CustomClass[]>>(); Or, instead of var n = ThisFunctionReturnsInteger(); I would write int n = ThisFunctionReturnsInteger();.

When do you use var?

I use var (almost) everywhere, mostly for aesthetic reasons. Obviously, I’ll make an exception when there are readability concerns, but I find that’s a pretty rare situation these days (at least in the codebases I work on).

Interesting, what do you work with if you don’t mind me asking?
It’s a convention: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions#implicitly-typed-local-variables

  • Use implicit typing for local variables when the type of the variable is obvious from the right side of the assignment, or when the precise type is not important.
  • Do not use var when the type is not apparent from the right side of the assignment.
  • Do not rely on the variable name to specify the type of the variable. It might not be correct.
  • Avoid the use of var in place of dynamic.
  • Use implicit typing to determine the type of the loop variable in for loops.
  • Do not use implicit typing to determine the type of the loop variable in foreach loops.

I only recently learned about the for loop convention. Anybody know why they recommend it? I have always just used an int

I agree with the general consensus of “if the right hand side makes it obvious”, but I’ll add on that sometimes I don’t need to know exactly what type an object is, for example IEnumerable<T> is often returned by LINQ operations, I don’t want to continually type IEnumerable<T> so I use var.
I also tend to do this unless I combine several queries and make a complicated operation.

Everywhere I can, only exception is when you have to declare some variable but the assignment happens further down.
Response response;

I use it whenever and whereever I can. I only use explicit type names if I have to because of casting etc. or if it is needed for readability (like when dealing with poorly named things outside my control)

I like to think that this makes me concentrate on naming things correctly and structuring my code better, which leads to other developers having a better time dealing with my code.

Do you somehow indicate the type in the variable name?
I do it exactly like you. When it’s clear what’s being returned (e.g., a call to a constructor), I use var. Else I tend to write out the return Type. Especially with long LINQ expressions I often have no idea what’s intended and I hate that I have to hover to see the return value.
Edit: I do it as recommended in the convention summarized by u/EnderStarways

You will spend more time reading code than writing it eventually – line length is not a good measure of readability, rather the time it takes to parse each sentence. Write code so that reading it is easy and clear, so if you need to read the code in an IDE and hover over a variable to understand the code, you probably do not want to use var or you need to make your intentions clearer with a better variable name.
In the latest version of the language you can use type inference with the new keyword so you can do:

Instead of:
This happens to be shorter and does not require the var keyword. Personally, I don’t mind either way as long as the code is readable.
Yeah, I saw this yesterday in the C# 9 spec-sheet. I should probably work on trying to implement this in my daily programming going forward. Thanks for the reminder!

I strongly concur with a few others here that –
If you feel the need to hover your mouse cursor over var in an IDE, then you shouldn’t have used that var.

IDE doesn’t solve the readability problem with var, despite what some people might argue. I doubt many people who argue so work in a big team on a huge codebase with lots of code reviews.

The guidelines on MS docs are good. In particular I want to highlight the point about not relying on method name for type information, as it can be subjective and unreliable.

Totally agree with this. I used to think you should always use var for readability because I know the IDE can help me out. In reality though, despite IDEs being extremely powerful these days you don’t always have their luxury – like parsing code on GitHub, DevOps, etc.

And in that case I think everyone else here has hit the nail pretty much right on the head.
for a while I was a “var skeptic”, i.e. I did not see any benefit for e.g. var x = 3; over int x = 3; – it’s not shorter, and it’s less specific. Ok, var is necessary for anonymous types, and it is useful for long complex generic types like the example that you give. But at first I thought that was all.
But this has changed over time to something simpler. Why? Think about minimising cognitive load: the simplest possible rule, that you don’t have to think about or weigh up a judgement call, is one that people gravitate to.

And that is: “use var wherever it is legal to.”
We have some devs who use Vim, for their sake we never ever use var. On my personal projects, I follow Microsoft’s guidance, more or less.
I don’t use C#, but Java has the same concept, and for this is syntactically identical, so I will provide a Java-oriented account that you should be able to retrofit to C# in the same way.

I use var when it is immediately obvious what the type is — either the assignment literally says it: ArrayList<String> names = new ArrayList<>(); is more readable as var names = new ArrayList<String>(); — or the type is overly complicated to type out.

Last I checked in C#, you guys don’t have diamond inference like we do, which means your declaration would be List<string> foo = new List<string>(); which in my personal opinion breaks the rule of “do not repeat yourself”, as you have specified the type twice in this assignment.
Generally as a rule, I use var or val (lombok) in most places where I do not need to assign a polymorphically compatible type, and where I don’t think it impacts readability or self documentability.

Exclusions of this can include:
… since var would change the type of the assignment and make this code result in a compilation error.
Another example in Java at least is when working with some integral types. long and int can have literals, but anything else is essentially cast for us. C# may or may not have short literals, I can’t remember honestly.

Generally I just use int unless there is an explicit reason to use short, as other than memory, there is very little reason to need to use it (most modern processors use a register size matching int, so using smaller datatypes just leads to unnecesarry masking, which can be slower if not dealt with on a hardware level); so these are very edge-casy.

I will often resort to use explicit types if assigning from the result of a method call where I don’t think it is immediately clear what the EXACT return type of a method is. I dont want to have to read documentation just to know what a piece of code is doing if i can help it. After all, I am a lazy person. Therefore a usage example could be double std = calculateStandardDeviation(...);. For you guys it might output a float, double, or decimal, so it is nice to be explicit.

The last thing that comes to mind is when hard casting, as like my first example, you can tell what the type is immediately. var foo = (ArrayList<Bar>) something;.

Using var where possible makes your declarations a bit more consistent, which can spare a few moments of thinking when scanning through a file quickly. It also means you can immediately find the definition of a variable by searching for var whatever in your editor.

Personally, I prefer how languages like Kotlin deal with declarations. They always use var/val and then add a type hint after the identifier only if needed. val foo: String. It vastly reduces the number of often redundant ways to say the same thing, which is nice in a team-managed code base as it ensures your code style is consistent for this kind of construct! 🙂

Not what you asked for directly, as I wouldnt like to give too much judgement on something I lack experience with, but from past usage, Java and C# share a lot of concepts with eachother, so hopefully this provides some beneficial examples to you until someone can explain better ones 🙂

In C# you absolutely can write var foo = new List<string>();
I use var always, unless I can’t. For example:
string someString = null;
int? someInt = 1;

About always if it’s functionally equivalent to specifying the type. There’s little reason not to if you can just hover over it and see the inferred type.
I only use defined types if I plan to use the variable as an “out” argument.
Otherwise I always initialize my variables.

I actually try not to care what type a variable is. But I might annotate an IEnumerable type with list. If it’s a list<T> or not. The point is it’s conceptually a list of things.

I’ve experimented with var thing = (ThingType) null; I like the consistency, but just feels stupid.

source