Search code examples
c#visual-studio-2022var

VS 2023 'var' suggestions


foreach (int dirId in dirIds)
{
    serieIds.AddRange((from serie in TableDataGrid.TargetBaseContext.Series
                       where serie.RepertoireId == dirId
                       select serie.SerieId).ToList());
}

In the above code, VS suggests to use var instead of int. Why should we, if only int is wanted ? Is there any way to tell VS not to suggest such modification ?

I just try to understand whether I miss something when thinking that int is better than var.


Solution

  • In Visual Studio, in the menu Tools > Options... you can navigate to Text Editor > C# > Code Style > General and configure 'var' preferences:

    enter image description here

    These are my personal preferences:

    • For built-in types var adds no value and only makes the code less readable
      => Prefer explicit type.

    • When the variable type is apparent as in var dict = new Dictionary<int, string>();, there is no point in repeating the type name. var makes the code more readable
      => Prefer 'var'.

    • Elsewhere: And then there are all these other cases. Sometimes you want to see the type as in List<PersonDto> = GetData();. In other cases - very often LINQ queries - the type names might become quite complex and add not much value. Or are you interested in the fact that a query returns a IOrderedEnumerable<(string Key, IEnumerable<IGrouping<string, Polygon>> Polygons)>? Here, I set the Severity to Refactoring only. This lets me refactor the code easily at any time without Visual Studio spamming me with irrelevant messages
      => Prefer explicit type + Refactoring only.