Craig Johnston
Craig Johnston

Reputation: 7607

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?

Upvotes: 1

Views: 1224

Answers (3)

jlnorsworthy
jlnorsworthy

Reputation: 3974

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.

Upvotes: -1

The Scrum Meister
The Scrum Meister

Reputation: 30111

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.

Upvotes: 2

BernzSed
BernzSed

Reputation: 1139

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).

Upvotes: 0

Related Questions