Wednesday, May 30, 2007

declaring variables inside a loop in c#

interesting thread here: http://www.thescripts.com/forum/thread505814.html

in the past (c++) it was best practice to avoid declaring variables inside a loop; in c#, both of these compile to the same IL:

for (int i = 0; i < 100; i++)
{
StringBuilder sb = new StringBuilder();
}

StringBuilder sb;

for (int i = 0; i < 100; i++)
{
sb = new StringBuilder();
}
and since the first example has the StringBuilder scoped to the for loop, you can’t accidentally use it after this code block executes. so: declare variables inside loops in c#.

No comments: