Your question really seems to boil down to the "How to Delete Material in C #" section. The short answer is: you cannot have the System.GC garbage collector working. IDisposable inerface is used to ensure that important resources not belonging to .Net (for example, files or network / database connections, but not the .Net class) are cleared on demand.
The IDisposable interface is important because it allows you to use the using template. That is, if your class implements IDisposable , it can be used in the using block. Consider, for example:
class MyClass : IDisposable { public void Dispose() { } }
Now this class can be used as follows:
using (MyClass instance = new MyClass()) { }
The point of the block used is that when the block ends, the compiler will call the Dispose() call, which you can use to get rid of important resources, such as files and database connections. For example, all Stream classes, such as FileStream and that do not implement IDisposable , because it is a bad idea to leave the file open. Instead, you terminate all your access in the using block, and then you are guaranteed that FileStream.Dispose will close the file. Consider:
using (FileStream myFile = File.OpenRead("...")) {
This is much neater than doing something like this:
FileStream stream = File.OpenRead(" ... "); stream.Close();
Now, what are you thinking about, this is a term called โFinalization,โ that is, when a class is actually destroyed. This happens when the garbage collector ( System.GC class) actually destroys the objects and clears their memory. Consider:
public class MyClass {
In short, the garbage collector is part of a runtime that cleans up material that is not in use. What does it mean not to use? This means that there are no references to the object. For example, if you run the program above, you will notice that the word "Destroyed" is printed twice on the screen. This is because two instances of MyClass created in the Main function are not referenced (A WeakReference is essentially the same as without a reference). When we call GC.Collect() , the garbage collector starts and clears the links.
However, you should NOT call GC.Collect yourself. Of course, you can experiment and learn, but most people will tell you that the garbage collector does an excellent job of keeping things clean. It doesn't make sense to have a bunch of GC.Collect scattered all over your code, because the whole point of having a garbage collector is no need to worry about cleaning yourself.
In short, you really can't destroy objects yourself unless you name GC.Collect() (which you shouldn't do). The IDisposable interface allows you to work with the using template, ensuring that important resources are released (this is not the same as destroying an object, though! Everything IDisposable does ensures that Dispose() is called when using blocks outputs, so you can clear important ones things, but the object is still alive - an important difference).