Skip to content

Implicit typing inside a foreach statement #20205

Open
@ghost

Description

I noticed something in the sample code at https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/intro-to-csharp/list-collection?tutorial-step=1

The example is using the var keyword inside the foreach statement. But the C# coding conventions here claim that implicit typing shouldn't be used for foreach loops.

This means that the following code is wrong

foreach (var name in names)
{
  Console.WriteLine($"Hello {name.ToUpper()}!");
}

and should be replaced with

foreach (string name in names)
{
  Console.WriteLine($"Hello {name.ToUpper()}!");
}

I'm not sure if this is considered an error since it's about coding style, but I thought that perhaps it will be worth pointing out.


Document Details

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions