Can anyone pls help how to dispose objects by my own. i.e i should not allow the garbage collector to dispose my object automatically when object is out of scope, instead it should leave the job of disposing the object to me whenever i need.


Thank You all

Can you elaborate on the reason why you want to do that?
As long as you use your object, it won't be disposed by the GC.

If your object requires special processing when the GC wants to clean it up, implement the IDisposable interface on your object.

I am working on a project about memory leaks, so i need my application to have some memory leaks.

Can anyone pls help how to dispose objects by my own. i.e i should not allow the garbage collector to dispose my object automatically when object is out of scope, instead it should leave the job of disposing the object to me whenever i need.

First of all, your classes must implements IDisposable interface (i.e implement Dispose method) and put clean up code in said Dispose method.

Read this article for reference.

I am working on a project about memory leaks, so i need my application to have some memory leaks.

C# doesn't provide 'good' methods for allocating memory (stackalloc) so your best results would be writing something in C and using interop to make calls for memory allocation. The garbage collector won't know about these allocations, so it won't touch the memory. If you want your application to be well behaved then you should maintain a list of the allocations (I'd do it in the C code) and provide a method to deallocate them when you are done.

This article has been dead for over six months. Start a new discussion instead.