For example, I have a Class A and a method f.
Class B
{
void aMethod(){}
}
void f()
{
var a= new B();
a.aMethod();
}
When execute a method, the CLR will first initiate essential type objects on heap. Thus before the first statement in f execute, an object B Type Object
will be allocated and initialized on heap.
So after f has been executed, will the B Type Object
be garbage collected?(Does B Type Object
has some special root
other than the B
Instance?)
For clarification, B Type Object
refers the System.Type
object that represents the B
type
I am reading chapter 4 of the book CLR via C#
.
After the f()
method finishes, the instance of the B
object created in the method becomes eligible for collection. That doesn't necessarily mean it will be collected right away. It will be collected whenever the GC happens to run next, which may or may not be when the method finishes.
But it also sounds like maybe you're talking about metadata, another kind of object instance used to describe object types, such as the Type
type.
So we need to talk about both things: Type
instances and metadata. There is no Type
instance just because you called the f()
method and used a B
object for the first time. There is metadata for each type, but it does not generally live on the heap, per se, and certainly isn't allocated only because you called f()
for the first time. Rather, all of the metadata for a particular assembly lives in a table in the object code for the assembly. The entire table is loaded with the assembly. You can read more about it here:
It's confusing, because there is also an Object
type, which means something completely different in .Net, and the use of the word Object
in the question confuses things more than it helps. But the Object
type in .Net is not automatically rooted in any special way. When instances are no longer reachable, they become eligible for collection just like anything else.