Using var or just another bike shedding

Guriy Samarin
2 min readSep 16, 2023

--

I tend to agree that using var in you code instead of concrete type — matter of developer taste. And it is mostly influence visual perception of the code (in non critical way). So wasting time on discussing it is useless. And telling that it is ruining your code review experience — is exaggeration. But… some things you can here about using var is not completely true. And even if the difference is subtle and not important in most cases — I want to highlight it:

Can var change type?

Yes, it can. Take a look

ICollection list = new List<string>();
foreach(var l in list)
{
}
foreach(string l in list)
{
}

In first loop l is object. And I know — IDE will tell you that, but still.

Can performance be affected by var?

Yes, it can.

ICollection list = new List<int>();
foreach(var l in list)
{
}
foreach(int l in list)
{
}

We have unboxing in second loop. And yes, in most scenarios we will do it later anyway. Still you could clearly think of situation in which it would affect performance (like we didn’t need value in majority of loop steps because of another check).

Can var be confusing?

Yes, it can. There is the issue then inline hint in IDE shows you type as nullable, but floating window (base on data flow analysis state it is not)

The reason is decision of the language design team to make all var variables nullable. IDE devs updated inlay hints to show actual data-flow based nullability.

References:

https://github.com/dotnet/csharplang/blob/main/meetings/2019/LDM-2019-12-18.md#var

https://youtrack.jetbrains.com/issue/RSRP-485536/var-variable-hint-shows-incorrect-type-if-NRT-enabled

--

--

Guriy Samarin
Guriy Samarin

Written by Guriy Samarin

Software developer at Amazon. Web (mostly backend) development now. My stack — .NET (APS.NET Core MVC).

No responses yet