IDisposable

A

Arjen

Hi,

Here I have made some sample code.
I want to know if I'm using IDisposable on the right way.

public class Person {
public string name;
public string address;
}

public class main {

try {
Person person = new Person();
person.name = "Arjen";
}
catch{
throw;
}
finally{
((IDisposable)person).Dispose();
}

}

Is the IDisposable useful here?
(I want that the object don't exist any more in the memory)

Thanks!
 
N

Nicholas Paldino [.NET/C# MVP]

Arjen,

IDisposable is used to indicate when an instance should release some
resource that is expensive. Almost all of the time, this is in reference to
something like a file handle, a socket, a database connection, or something
like that. It doesn't do anything to indicate that the object will exist
anymore in memory.

You can't control when the object is released from memory, that's what
the GC is for.

Hope this helps.
 
G

Guest

Since class Person does not implement IDisposable the cast will fail at
runtime. It is not useful though, because you are not using any unmanaged
resources, streams, or the like. Implement idisposable for classes that use
things like COM calls, database connections, file streams...
 
A

Arjen

Okay, thank you all.



Nicholas Paldino said:
Arjen,

IDisposable is used to indicate when an instance should release some
resource that is expensive. Almost all of the time, this is in reference
to something like a file handle, a socket, a database connection, or
something like that. It doesn't do anything to indicate that the object
will exist anymore in memory.

You can't control when the object is released from memory, that's what
the GC is for.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Arjen said:
Hi,

Here I have made some sample code.
I want to know if I'm using IDisposable on the right way.

public class Person {
public string name;
public string address;
}

public class main {

try {
Person person = new Person();
person.name = "Arjen";
}
catch{
throw;
}
finally{
((IDisposable)person).Dispose();
}

}

Is the IDisposable useful here?
(I want that the object don't exist any more in the memory)

Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top