C# Interview Questions on Destructors

Q : What is a Destructor?

Ans : A Destructor has the same name as the class with a tilde character and is used to destroy an instance of a class.

Q : Can a class have more than 1 destructor?

Ans : No, a class can have only 1 destructor.

Q : Can structs in C# have destructors?

Ans : No, structs can have constructors but not destructors, only classes can have destructors.

Q : Can you pass parameters to destructors?

Ans : No, you cannot pass parameters to destructors. Hence, you cannot overload destructors.

Q : Can you explicitly call a destructor?

Ans : No, you cannot explicitly call a destructor. Destructors are invoked automatically by the garbage collector.

Q : Why is it not a good idea to use Empty destructors?

Ans :When a class contains a destructor, an entry is created in the Finalize queue. When the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this just causes a needless loss of performance.

Q : Is it possible to force garbage collector to run?

Ans :Yes, it possible to force garbage collector to run by calling the Collect() method, but this is not considered a good practice because this might create a performance over head. Usually the programmer has no control over when the garbage collector runs. The garbage collector checks for objects that are no longer being used by the application. If it considers an object eligible for destruction, it calls the destructor(if there is one) and reclaims the memory used to store the object.

Q : Usually in .NET, the CLR takes care of memory management. Is there any need for a programmer to explicitly release memory and resources? If yes, why and how?

Ans :If the application is using expensive external resource, it is recommend to explicitly release the resource before the garbage collector runs and frees the object. We can do this by implementing the Dispose method from the IDisposable interface that performs the necessary cleanup for the object. This can considerably improve the performance of the application.

Q : When do we generally use destructors to release resources?

Ans :If the application uses unmanaged resources such as windows, files, and network connections, we use destructors to release resources.

Leave a Reply
Name (required)
Email (will not be published) (required)
Web Site

List of Top Hospitals in India