Skip to main content
Question Protected by gnat
Tweeted twitter.com/#!/StackProgrammer/status/642032817111724032
deleted 248 characters in body
Source Link
Robert Harvey
  • 200.1k
  • 55
  • 468
  • 679

I have a feeling this question has been asked a million times but I wasn't able to find a C# version of it. Before I continue I want to make it clear that I am in no way attempting to do premature optimization here. Just my curious side asking.

Is there a difference between these two versions of code?

foreach (var thing in things)
{
    int i = thing.number;
    // code using 'i'
    // pay no attention to the uselessness of 'i'
}

int i;
foreach (var thing in things)
{
    i = thing.number;
    // code using 'i'
}

Or does the compiler not care? When I'm speaking of difference I mean in terms of performance and memory usage. ..Or basically just any difference or do the two end up being the same code after compilation?

I have a feeling this question has been asked a million times but I wasn't able to find a C# version of it. Before I continue I want to make it clear that I am in no way attempting to do premature optimization here. Just my curious side asking.

Is there a difference between these two versions of code?

foreach (var thing in things)
{
    int i = thing.number;
    // code using 'i'
    // pay no attention to the uselessness of 'i'
}

int i;
foreach (var thing in things)
{
    i = thing.number;
    // code using 'i'
}

Or does the compiler not care? When I'm speaking of difference I mean in terms of performance and memory usage. ..Or basically just any difference or do the two end up being the same code after compilation?

Is there a difference between these two versions of code?

foreach (var thing in things)
{
    int i = thing.number;
    // code using 'i'
    // pay no attention to the uselessness of 'i'
}

int i;
foreach (var thing in things)
{
    i = thing.number;
    // code using 'i'
}

Or does the compiler not care? When I'm speaking of difference I mean in terms of performance and memory usage. ..Or basically just any difference or do the two end up being the same code after compilation?

Source Link
Alternatex
  • 1k
  • 2
  • 13
  • 24

Foreach loop and variable initialization

I have a feeling this question has been asked a million times but I wasn't able to find a C# version of it. Before I continue I want to make it clear that I am in no way attempting to do premature optimization here. Just my curious side asking.

Is there a difference between these two versions of code?

foreach (var thing in things)
{
    int i = thing.number;
    // code using 'i'
    // pay no attention to the uselessness of 'i'
}

int i;
foreach (var thing in things)
{
    i = thing.number;
    // code using 'i'
}

Or does the compiler not care? When I'm speaking of difference I mean in terms of performance and memory usage. ..Or basically just any difference or do the two end up being the same code after compilation?