C#: variable declaration inside loop
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.
精彩评论