Reputation: 317
In C# 3.5 in a class I have a few static methods with some variables. Static methods are initialized first even if I do not initialize the class.
So are the variables inside the static methods also initialized in the beginning and not garbage collected ?
I want to know - will the memory be allocated for such method-variables even if I do not call the method or I call the method once and the method exits ? Or every time the method is called and it exits - the variables inside a method are garbage collected ?
Upvotes: 1
Views: 1997
Reputation: 148120
Static method variable are created when method is called and will go out of scope when method execution ends and they become ready for being garbage collected.
Upvotes: 1
Reputation: 1062865
Static methods are initialized first
no, static methods aren't "initialized" as such; they are (in standard implementations) JITted on first usage, but that is unrelated to memory allocations.
So are the variables inside the static methods also initialized in the beginning and not garbage collected ?
method variables are per call (on the stack) - not globally; the stack space is assigned as you enter the method. If you have reference-type variables, they will go out of scope when the method exits (assuming those variables aren't "captured" into a delegate or lambda expression that lives longer that the method).
Only objects are garbage collected; not variables. Reference-type variables just hold a reference to the object.
Upvotes: 8