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.
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.
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.
MyObject myObj; for(...){ MyObject myObj }will not work.