简体   繁体   中英

C#: variable declaration inside loop

Is the following code correct?

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

Can you declare a variable 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM