+ 1
Am I understanding these concepts correctly?
I recently read the concept of "variable lifetime" and "variable visibility range" as I understand it: Lifetime - if I exit the body of the loop, will the variable be destroyed? Visibility range - a variable created in a loop is not visible outside of it?
5 Respuestas
+ 4
Yes, almost. Small detail: We don't know when the variable will be destroyed.
C# has a "garbage collector" that picks up the garbage every so often. So once you exit the loop body, the variable will be destroyed the next time the garbage collector runs. We don't know when that is, but it will happen eventually.
That detail doesn't matter in most cases because as you said, the variable isn't visible outside the loop anyway, but it is worth pointing out. Sometimes it does matter :)
+ 3
I want to clarify a small detail, the garbage collector is launched every time after exiting the loop?
+ 3
When the garbage collector runs depends on many factors, like how much RAM do you have, how many objects are you creating in your code, how long has your program been running (some software runs for years! No need to garbage collect every half second), etc etc.
We're not supposed to know or care when the GC runs, but it probably doesn't run after every loop no :) It's a sophisticated piece of software and the programmer shouldn't interfere even though we could (`System.GC.Collect()`)
You have to keep in mind the distinction between a variable, and what is stored in it. It's content can change, and a variable is just a placeholder name that exists in your code. Variables aren't really "destroyed", they just go "out of scope", for example after the loop body. That means it's no longer accessible by other code.
And once a variable goes out of scope, the contents of the variable will be marked for garbage collection.
+ 2
1st : yes only if it created in loop.
2nd: yes. answered already in 1st. it's a same question almost
+ 1
Thanks for the clarification!