Search code examples
c#dispose

Should dispose be mandatorily used for all objects


I have a function wherein i have created an object for a class, to use it inside the function and return it to the calling funciton.

Myobj read(string s)
{
   Myobj obj = new Myobj ();
   ..................
   ........................
    return obj
 }

In this case should i mandatorily dispose the object i have created.

Also when should i use destructor,dispose , finalize


Solution

  • The only reason you ever need to worry about Dispose()/IDisposable is if you're dealing with a resource other than memory. This includes database connections, sockets, GDI resources, file streams, and some other things. If you just have a POCO (plain old CLR object), there is no need for IDisposable.

    The only reason you ever need to worry about a finalizer is if you're already building a type that implements IDisposable, and there is not already a .Net class that will finalize this resource. Everything mentioned above (database connections, sockets, GDI resources, and file streams) already has a .Net class that will finalize the resource, and so you do not need a finalizer, unless you're doing something like building a whole new kind of database.