ReSharper usually suggests me that, and I’m still looking for a good reason of why to do that.
The only thing that came to my mind is that declaring it closer to the scope it will be used, can avoid initializing it in some cases where it isn’t necessary (because a condition, etc.)
Something related with that is the following:
int temp;
foreach (var x in collection) {
temp = x.GetValue();
//Do something with temp
}
Is that really different than
foreach (var x in collection) {
int temp = x.GetValue();
//...
}
I mean, isn’t the second code more expensive because it is allocating memory everytime? Or are both the same? Of course, after finished the loop, in the second code the garbage collector will take care about temp variable, but not in the first one…
The cost of the second example is negligible. The only difference is that in the first example,
tempwill be available outside the scope of theforloop, and thus it will exist longer than if you declared it inside theforloop.If you don’t need
tempoutside theforloop, it shouldn’t be declared outside that loop. Like others have said, readability and style are more at play here than performance and memory.