Friday, July 31, 2020

C#: When/When Not to Use var

I am sure everyone knows what var keyword is, it is one of the most heavily used types/keywords in C#. It was introduced with C# 3.0, and when used in the right way, it's wonderful. But when it's used in the wrong way, it can make the code less readable and lead to issues as well. 

So in this post, let's see when and when not to use var.

First, let's see when to use var
var number = 10; // number => int

var text = "Hello World"// text => string
var items = weatherForecasts // items => List<T>
    .Where(x => ...)
    .ToList();

for (var i = 0; i < 1000; i++) // i => int
{ ...
} int.TryParse("5", out var i) // i => int
For me, above are the perfect candidates to use implicit typing (var) rather than explicit typing, because when we are reading the code, we can determine what the type of the variable is by just looking at the right side.

But consider these:
var forecasts = GetWeatherForecasts();

foreach (var forecast in forecasts)
{

}
For me, these are pretty bad use of var. For example, GetWeatherForecasts() method can be returning a Task where we need to await on. We won't know until we closely examine the method.

Consider below sample code.
[HttpGet]
public async Task<IActionResult> Get()
{
    // This hides the warning we are using async without await
    await DoSomething();

    // this is actually returning a task where we need to await on
    var forecasts = GetWeatherForecasts();

    return Ok(forecasts);
}
If we invoke this endpoint, the output will be something like this which is not what we expect to return.
Output
In Visual Studio you can set up a rule to configure the code style related to var. You can find it inside Tools -> Options -> Text Editor -> C# -> Code Style -> General.
Code Style
More read:

Hope this helps.

Happy Coding.

Regards,
Jaliya