fxcop - Dispose pattern analysis

A

AlexS

When I implement Dispose pattern in object implementing IDisposable, current
fxcop recommends:

Ensure that Wrapper.Dispose():Void is declared as public and sealed.

However, if I do as it asks, compiler complains that sealed can't be used
because method is not overrideable.

I believe sealed isn't applicable here at all. And this rule shouldn't be
public virtual in this case.

Am I right or do I miss something important?
 
H

Henning Krause [MVP - Exchange]

Hello,

the correct implementation is as follows:

public class Test: IDisposable
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Dispose any nested instances
}
// free unmanaged resources, do not access nested instances any
more, as they could be freed by the GC already
}
}

If your class has a destructor, simply call Dispose(false) from it.

Best regards,
Henning Krause
 
A

AlexS

Thanks, Henning, fxcop likes that.

Why MS recommends "public Dispose" implementation and not "public virtual
Dispose"?

When subclassing I can override Dispose and extend its functionality using
"new Dispose" declaration. So, why to insist on omitting virtual?

Question is more academic, I believe, however, fxcop is mixing me up
sometimes with it's Dispose pattern analysis.

Another question - related - is: I am subclassing class implementing
IDisposable. Forms designer generates Dispose(bool) in this case overriding
base implementation. I don't want to touch designer code as it could be
regenerated and maybe my changes will be cancelled. So, I implement "public
new Dispose" in subclass. And fxcop recommends then this:

Ensure that TableTab.Dispose():Void is declared as public and sealed.

Which is impossible as Dispose is not an override - it is "public new". And
base implementation doesn't specify "virtual".

So, what fxcop means in this case?

Alex
 

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