Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this really an improvement (moving var to inner scope when inner scope is in a loop)?

Tags:

Resharper recommends that these vars:

List<string> senderDeviceIDList; string senderDeviceID; . . .             foreach (var item in PlatypiIds)             {                 senderDeviceIDList = await GetSenderDeviceIDForSenderID(item);                 senderDeviceID = senderDeviceIDList[0]; 

...can be declared in inner scope, like so:

    foreach (var item in PlatypiIds)     {         List<string> senderDeviceIDList = await GetSenderDeviceIDForSenderID(item);         string senderDeviceID = senderDeviceIDList[0]; 

...but is that really "more better"? Doesn't that cause the vars to be declared N times (once for each foreach loop)?

like image 772
B. Clay Shannon-B. Crow Raven Avatar asked Dec 17 '12 21:12

B. Clay Shannon-B. Crow Raven


People also ask

Is var global scope?

The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value.

When the variable scope is available only within the method where it is defined?

When the variable scope is available only within the method where it is defined, then that variable is called as a local variable.


1 Answers

There is no any benefit in terms of performance or memory allocation here, as variables inside or oustside of the if scope are declared in the IL, by the way.

The only benefit is localization of the variable scope. Move it to the scope where it's used, which brings goodness like:

  • easy refactoring (may be the most important)

  • readability. If you see variable inside the scope, you know that its used only inside that scope and if you see some variable that apparently is not inside, you know that changing it can affect other parts of the code. So changing it introduce some potential danger.

In short, it's about readability and usability of the code you're writing and does not introduce any performance or memory consumption benefits.

like image 170
Tigran Avatar answered Oct 30 '22 03:10

Tigran