When I'm implemeting IDisposable interface, I've work with the bool disposed
variable, which is in protected virtual void Dispose(bool disposing)
.
But I wonder, what if I use not a simple variable, but the property in C# with this situation?
class A : IDisposable
{
bool disposed { get; set; }
...
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
//dispose managed ressources
}
}
disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
This property:
bool disposed { get; set; }
is almost equivalent to a field. It's effectively this:
bool _disposed;
bool disposed { get { return _disposed; } set { _disposed = value; } }
Given that both the field and the property are private, and you're not adding any behaviour to the property, I'd just stick with a simple field.
Also note that if you can seal your class (so you don't need to worry about subclasses wanting to override Disposing(bool)
you can get rid of the Dispose(bool)
method entirely, and just implement Dispose()
in a simple way.
Indeed, unless you need to keep a flag indicating whether or not the instance has been disposed, you could remove that, too.
See more on this question at Stackoverflow