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 ?
no, static methods aren’t “initialized” as such; they are (in standard implementations) JITted on first usage, but that is unrelated to memory allocations.
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.