1

Is the following code correct?

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

Can you declare a variable more than once?

1
  • 3
    Define "more than once". You can define it if it's not within the function, having local scope override the more global scope. however, MyObject myObj; for(...){ MyObject myObj } will not work. Commented Mar 8, 2011 at 4:57

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ahead of me by 12 seconds! StackOverflow has really forced me to get on top of my typing speed!
+1 for mentioning the scope. I was also answering on the same line.
0

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

Comments

-1

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.

10 Comments

Please given two loops with identical semantics, one where a variable in question is declared inside the loop, and another where it is declared outside the loop and the performance is markedly different between the two loops.
@Jason - Which is why I mentioned the performance concern. Perhaps you can let us know how many iterations a trivial loop must run where declaring a variable inside the loop results in a real world performance concern.
@jlnorsworthy: Wait, you're the one that stated it can be detrimental to performance. My claim is that it's not, and I'm challenging you to prove me wrong.
@Jason: Here: ideone.com/laNz3 Just you try moving that variable declaration inside the loop and we'll see how patient you are. Of course you must run it on your own machine, because ideone would time out after only a few seconds.
@Ben Voigt: I can see this descending into an argument about semantics, but I claim that code snippet has different semantics depending on whether or not i is declared in the loop or out of the loop. The observable semantics are the same, but the internal semantics are not because different numbers of instances of the compiled-generated class that i is hoisted to are created depending on whether or not i is declared in the loop or out of the loop. If you put a Console.WriteLine("Hello, world!") in the constructor for that class, you would see different output for the two versions.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.