简体   繁体   中英

If I assign null to an object or a property, will the garbage collector in C# always run and release its memory space?

A a = new A();
a.Name = null;

Will the garbage collector release the properties' space?

In addition:

B b = new B();
b = null;

Will the garbage collector release the objects' space?

In your first example a.Name only occupies so much space as is needed to hold a reference to an object of a.Name 's type. Wether it contains null or a reference does not matter. This space will only get collected when the whole object a gets collected. An object which a.Name points to might be collected when you set a.Name to null .

In your second example, b might or might not get collected.

In any case you can't trigger a garbage collection just by assingning null as the collection can occur at any time the runtime sees fit. You might want to read the details in the documentation .

First case is not clear what is the Name . If it is a string then yes, setting it to null will release the memory eventually. If it is a class then it may or may not but that is covered by your second question.

So in the second case if this is all the code of your app the memory will be eventually released. However one object can have multiple references or subscription to some event that may prevent it from being garbage collected so just setting the initial reference to the null is not something that grants collection in each case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM