Junior — Middle
Can you explain the concept of an object's or variable's lifetime in a program?
sobes.tech AI
Answer from AI
The duration of an object's or variable's existence is the period during which the object or variable occupies memory and is accessible for use in the program.
In C#, the lifetime depends on the scope and type of the variable:
- Local variables exist only during the execution of the code block (e.g., a method). After exiting the block, memory is released for them.
- Object fields exist as long as the object itself exists. An object in the heap lives until there are no references to it, after which the garbage collector frees the memory.
- Static variables exist throughout the entire runtime of the application.
Example:
class Program
{
static int staticCounter = 0; // lives throughout the program's runtime
void Method()
{
int localVar = 5; // exists only during the method's execution
var obj = new MyClass(); // the object lives as long as there are references to it
}
}