Skip to content

Provide a reason why implicit typing should be avoided in loop variable in foreach loops #27367

@NagayamaToshiaki

Description

@NagayamaToshiaki

According to C# Coding Conventions, "Don't use implicit typing to determine the type of the loop variable in foreach loops."
But no clear reason is written here, so I don't know why we should use foreach (char ch in laugh) instead of foreach (var ch in laugh).
You can find usually easily which type the var is, as Intellisense suggests like other vars.

Dictionary<Foo, Bar> X = new();
// Add some elements to X...
foreach(KeyValuePair<Foo, Bar> Y in X)
{
// Some Process here
}

Above might be difficult to guess, but that is what the C# implementation of Dictionary is, so not hard to remember.

Is this rule relevant to the note below it("Be careful not to accidentally change a type of an element of the iterable collection...")?


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions