Is it better to declare a variable inside or outside a loop?

后端 未结 6 2001
眼角桃花
眼角桃花 2020-12-01 07:55

Is better do:

variable1Type foo; 
variable2Type baa; 

foreach(var val in list) 
{
    foo = new Foo( ... ); 
    foo.x = FormatValue(val); 

    baa = new B         


        
6条回答
  •  臣服心动
    2020-12-01 08:17

    It's just a matter of scope. In this case, where foo and baa are only used within the for loop, it's best practice to declare them inside the loop. It's safer too.

提交回复
热议问题