Manually destroy C# objects
You don't manually destroy .Net objects. That's what being a managed environment is all about.
In fact, if the object is actually reachable, meaning you have a reference you can use to tell the GC which object you want to destroy, collecting that object will be impossible. The GC will never collect any object that's still reachable.
What you can do is call GC.Collect()
to force a general collection. However, this almost never a good idea.
Instead, it's probably better to simply pretend any object that doesn't use unmanaged resources and is not reachable by any other object in your program is immediately destroyed. I know this doesn't happen, but at this point the object is just a block of memory like any other; you can't reclaim it and it will eventually be collected, so it may just as well be dead to you.
One final note about IDisposable
. You should only use it for types that wrap unmanaged resources: things like sockets, database connections, gdi objects, etc, and the occasional event/delegate subscription.
Destroy an object in C#
Do nothing. Your reference (obj) will go out of scope. Then the Garbage Collector will come along and destroy your object.
If there are (unmanaged) resources that need to be destroyed immediately, then implement the IDisposable interface and call Dispose in the finalize block. Or better, use the using statement.
EDIT
As suggested in the comments, when your ClassName implements IDisposable, you could either do:
ClassName obj = null;
try{
obj = new ClassName();
//do stuff
}
finally{
if (obj != null) { obj.Dispose(); }
}
Or, with a using statement:
using (var obj = new ClassName())
{
// do stuff
}
Related Topics
Questions About Entity Framework Context Lifetime
How to Install a Windows Font Using C#
How to Change the Culture of a Winforms Application at Runtime
Find If Point Lies on Line Segment
Visualizing an Ast Created with Antlr (In a .Net Environment)
Comparing 2 Objects and Retrieve a List of Fields with Different Values
Is There an Entity Framework 7 Database-First Poco Generator
Print Fixeddocument/Xps to PDF Without Showing File Save Dialog
A Way to Push Buffered Events in Even Intervals
Server.Mappath - Physical Path Given, Virtual Path Expected
Usage of Ioc Containers; Specifically Windsor
C# - Inconsistent Math Operation Result on 32-Bit and 64-Bit
How to Create a New Operator in C#
How Does Stringbuilder Work Internally in C#
Accessing a Property of Derived Class from the Base Class in C#