In C#, why assign member variables to local variables and then use local variables instead of using member variables directly, as shown in the following snippet:
internal class LocalVariableTest
{
private readonly int[] _items = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
public void ConsoleWriteLine()
{
var items = _items;
foreach (var item in items)
{
System.Console.WriteLine(item);
}
}
public void ConsoleWriteLine2()
{
foreach (var item in _items)
{
System.Console.WriteLine(item);
}
}
}
What is the difference between ConsoleWriteLine and ConsoleWriteLine2?
I would like to know if there is any difference between the two methods after compiling. I have seen many places that have this way of writing. Which one has higher performance and where is the knowledge about this, such as Microsoft Learn?