I saw something today talking about this:
aClass something;
while (condition) {
something = new aClass();
...
}
while (condition) {
aClass something = new aClass();
...
}
It said you should use the second one rather than the first. Is this true, and if so, why?
The second method keeps the
somethingvariable only in the scope of that specific loop iteration.If you want to use the object outside the loop and / or keep the changes saved between iterations then you must use the first method.
Also, the second method doesn’t define multiple variables, the compiler will usually optimize it in a way that makes sure only one variable is defined.