Am I understanding these concepts correctly? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

22nd May 2021, 6:46 PM
‎أندريه‎
‎أندريه‎ - avatar
5 Answers
+ 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 :)
22nd May 2021, 11:04 PM
Schindlabua
Schindlabua - avatar
+ 3
I want to clarify a small detail, the garbage collector is launched every time after exiting the loop?
23rd May 2021, 7:54 AM
‎أندريه‎
‎أندريه‎ - avatar
+ 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.
23rd May 2021, 9:37 AM
Schindlabua
Schindlabua - avatar
+ 2
1st : yes only if it created in loop. 2nd: yes. answered already in 1st. it's a same question almost
22nd May 2021, 7:12 PM
Jayakrishna 🇮🇳
+ 1
Thanks for the clarification!
23rd May 2021, 9:44 AM
‎أندريه‎
‎أندريه‎ - avatar