I have the following code.
baseclass bc = new derivedclass();
Will the base class object be created in this case? If yes how will the GC know that it is being used (as it does not have any variable pointing to it)? How does the GC handle this?
EDIT : When I set bc = null, Both the base and derived class destructors are called. If no base object is created, how is it calling base class destructor?
How can the destuctor be called when there is no base object?
This is what MSDN says about destructor : “Destructors are used to destruct instances of classes”.
No, only an instance of the derived class is created. That will contain all of the fields of the base class, of course, but it isn’t a separate object. There’s nothing to be garbage collected.
Note that
bcis just a variable, not an object.bcitself doesn’t need to be garbage collected – it’s just that it can prevent the garbage collection of the variable whose value it refers to if it might be read again. (If nothing is ever going to read frombcagain, and you’re not running under the debugger, it won’t prevent the object from being garbage collected.)