-
Notifications
You must be signed in to change notification settings - Fork 4
Gendarme.Rules.Exceptions.UseObjectDisposedExceptionRule(git)
Assembly: Gendarme.Rules.Exceptions
Version: git
It's usually a very bad idea to attempt to use an object after it has been disposed. Doing so may lead to crashes in native code or any number of other problems. In order to prevent this, and to report the problem in a clear way, classes should throw System.ObjectDisposedException from public methods if the object has been disposed. Note that there are some methods which should not throw ObjectDisposedException. This includes constructors, finalizers, Equals, GetHashCode, ToString, and Dispose.
Bad example:
internal sealed class WriteStuff : IDisposable
{
public WriteStuff (TextWriter writer)
{
this.writer = writer;
}
// Objects are generally not in a useable state after being disposed so
// their public methods should throw ObjectDisposedException.
public void Write (string message)
{
writer.Write (message);
}
public void Dispose ()
{
if (!disposed) {
writer.Dispose ();
disposed = true;
}
}
private bool disposed;
private TextWriter writer;
}
Good example:
internal sealed class WriteStuff : IDisposable
{
public WriteStuff (TextWriter writer)
{
this.writer = writer;
}
// In general all public methods should throw ObjectDisposedException
// if Dispose has been called.
public void Write (string message)
{
if (disposed) {
throw new ObjectDisposedException (GetType ().Name);
}
writer.Write (message);
}
public void Dispose ()
{
if (!disposed) {
writer.Dispose ();
disposed = true;
}
}
private bool disposed;
private TextWriter writer;
}
- This rule is available since Gendarme 2.6
You can browse the latest source code of this rule on github.com
Note that this page was autogenerated (3/17/2011 1:55:44 PM) based on the xmldoc
comments inside the rules source code and cannot be edited from this wiki.
Please report any documentation errors, typos or suggestions to the
Gendarme Mailing List. Thanks!