Don’t use the C# var keyword everywhere in your code just to be consistent

Don’t use the var keyword everywhere in your code base just to be consistent. If using var removes clarity for certain assignments its best not to use it in these cases.

Example 1 below shows some usages of var in which the type is very clear from the right hand side. In these cases var is a nice addition as it improves readability as the variable names are all aligned and the type is not repeated.

On the other hand example 2 shows how var can be misused and ends up actually removing clarity as its not clear what the type is.

Var keyword examplesOf course when the type is not clear we can always mouse over the variable name and VS intellisense will tell us the type. This however is extra work and intellisense is not available in all contexts such as when viewing code online on GitHub etc.

Looks like its from 2015 but here are some Microsoft recommendations on implicitly typed variables.

Leave a Reply

Your email address will not be published. Required fields are marked *