docs icon indicating copy to clipboard operation
docs copied to clipboard

Implicit typing inside a foreach statement

Open ghost opened this issue 5 years ago • 1 comments

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.

ghost avatar Aug 20 '20 16:08 ghost

Thanks for writing this @nathaniades

I've added it to our backlog for the next time we update this article.

BillWagner avatar Aug 20 '20 17:08 BillWagner