I've been reading about IDisposable interface lately (this topic was quite useful Proper use of the IDisposable interface) and also about usage of using statement (topic Uses of "using" in C#). Then I started wondering what if I should somehow free my own collection class from memory.
class User{
private string username {set;get;}
private string password {set;get;}
...
}
Should it implement IDisposable interface?
class User : IDisposable
{
...
public void Dispose()
{
this.Dispose();
}
}
so it could be freed from memory? Or does GC do it automaticly and I shouldn't even bother about it.
As far as I understand it's important to free unmanaged resources like DB connections and such but what about those collection classes. Since I use them quite frequently It really started to bug me.
tl;dr; should I implement IDisposable on User class?
Kind Regards.
edit: thanks everyone for the replies!
Or does GC do it automaticly and I shouldn't even bother about it.
This. Unless you have unmanaged resources (either directly or by way of a reference to something else which is disposable), you almost certainly shouldn't implement IDisposable
.
Your current implementation would just call itself:
public void Dispose()
{
this.Dispose();
}
... so assuming you don't really want to call this.Dispose()
, what would you want to do when Dispose()
is called? It's not like disposal causes garbage collection - so what action do you want to take? If the answer is "nothing" then you probably shouldn't be implementing IDisposable
. (The exception here is if this is designed to be a base class and you're expecting some derived classes to require disposal... that's a more complex scenario.)
See more on this question at Stackoverflow