   [.net] delete object
  How can I delete an object in C#? (is it possible?)object = null; doesn't delete the object.   
Quote:Original post by frankfrankHow can I delete an object in C#? (is it possible?)object = null; doesn't delete the object.Unfortunately, you can't really control when an object is destroyed. You can invoke the garbage collector manually, but then you are working against its principles and probably end up with a performance bottleneck. Many classes provide a Dispose() method, with which you can tell objects to please release required resources, but the object itself is still dangling around until the GC finds some time.If you're plan somehow includes RAII functionality, you can work with a try/finally block:void foo () {   try {   } finally { // gets executed in every case   }}But that's a kludge as well. Coming from C++, I think the lack of RAII is a major disadvantage in C#.Anyhow, what do want to achieve by "deleting" said object?   ;  Indeed, it is possible. Read up on the disposable pattern.In short, use this code snippet to ensure deterministic deallocation:sealed class Foo : IDisposable{    bool disposed;    public Foo() { /* Allocate resources */ }    public void Dispose()    {   Dispose(true);   GC.SuppressFinalize(this);    }    void Dispose(bool manual)    {   if (!disposed)   {  if (manual)  { /* Deallocate resources */ }  else  { /* Called from finalizer thread: deallocate if it's safe, or log an error if it's not */ }  disposed = true;   }    }    ~Foo()    {   Dispose(false);    }}Now, use Foo like this:using (Foo foo = new Foo()){}Foo will be disposed automatically as soon as it leaves the using block.Edit: Dispose() should call Dispose(true). Fixed.[Edited by - Fiddler on June 17, 2009 9:45:02 AM];Quote:Original post by FiddlerIndeed, it is possible. Read up on the disposable pattern.In short, use this code snippet to ensure deterministic deallocation:*** Source Snippet Removed ***Now, use Foo like this:*** Source Snippet Removed ***Foo will be disposed automatically as soon as it leaves the using block.I fail to reproduce this in C# 3.5. Even upon debugging and optimisations turned off, I don't land in ~Foo(). At the danger of this becoming a rant, in C++ you'd just write struct X {    X() {}    ~X() {}}int main () {    X x;}and be that ~X() gets called as soon as scope is left. Even when using heap-allocation, it's just:int main () {    scoped_ptr<X> x (new X);}and you have the guarantee it gets called upon leaving scope. Another question: Is it really necessary that Foo is sealed in your example?   ;  Okay, I see. You have to write the actual destruction code in Dispose(bool), not in the actual destructor or Dispose(). Whoa, so many potential points of programming failure for just a simple deterministic deletion. And the burden is even exposed to client code  ... I wonder why Microsoft does not just implement a delete operator (which would then be syntactic sugar into the GC or some wrapper around Disposables). While still cumbersome and complex under the hood, it would be far less error prone.Thanks Fiddler for your post.edit: I recognize that I can only have multiple variables of the same type in a using declaration. Hm.   ;  The notation is misleading: ~Foo() is a finalizer, not a destructor! Semantically, the destructor is Dispose() (which is why the deallocation must take place there.) Calling (C#) 'foo.Dispose();' is equivalent to (C++) 'delete foo;'The underlying issue is that .Net uses a mark & sweep garbage collector, which doesn't give you any control over when the finalizer will run (not in the general case, at least.) This is a fundamentally different programming model than manual memory management or reference counting GCs: simply put, it trades deterministic finalization for performance.There is no reason why Foo has to be sealed, other than keeping the implementation simple. When dealing with IDisposable, a good rule of thumb is to keep your class as simple as possible: it's better to use composition (class Bar has fields Foo, Baz, which implement IDisposable) rather than inheritance (class Bar inherits Foo, contains Baz and must deal with deallocating both managed and unmanaged resources). If you decide to use inheritance, consider changing 'private void Dispose(bool manual)' to 'protected virtual void Dispose(bool manual)' and overriding the implementation in the inheriting class.Finally, if you need to allocate a large number of IDisposable resources, consider using a resource manager or object pool. This way it will be easier to dispose or reuse resources as needed. The BCL uses this pattern extensively, e.g. by pooling threads, database connections etc etc.Edit: Don't forget that you can do this:using (Foo foo = new Foo())using (Bar bar = new Bar()){};  I see. Thanks for the enlightenment :D   ;  The more important question is why do you think you NEED to delete something?theTroll   ;Quote:Original post by FiddlerIndeed, it is possible. Read up on the disposable pattern.In short, use this code snippet to ensure deterministic deallocation:*** Source Snippet Removed ***This snippet is wrong. take a look at your finalizer vs your dispose method.;  Thanks, fixed.Edit:Quote:The more important question is why do you think you NEED to delete something?There are many legitimate reasons for deterministic deallocation of resources. Imagine OpenGL buffers, network connections, file handles, kernel objects... many of these may only be freed from the thread they were allocated on (i.e. not from the finalizer). Others represent limited commodities and should be freed as soon as possible.   