开发者

C#: variable declaration inside loop

开发者 https://www.devze.com 2023-02-15 05:38 出处:网络
Is the following code correct? foreach (int i in MyList) { MyObject m; } Can you declare a 开发者_如何学JAVAvariable more than once?You are not declaring it more than once. Variables have a \"scope

Is the following code correct?

foreach (int i in MyList)
{
    MyObject m;
}

Can you declare a 开发者_如何学JAVAvariable more than once?


You are not declaring it more than once. Variables have a "scope", and the scope of the m variable ends at the end } before the next iteration.


Yes.

If I remember my C# correctly, when executed, it is only declared once, but the variable is re-used until the end of the scope (not the end of each loop).


You can declare a variable inside a loop. If it is only needed inside the loop, it is preferable for code readability. It can possibly be detrimental to performance, but you would only need to worry about that if the variable in question was expensive to declare and instantiate, or your list was extremely large.

0

精彩评论

暂无评论...
验证码 换一张
取 消