DaveDev DaveDev - 1 month ago 11
C# Question

Why does class implementing IDispose not have OnDisposed override?

I have a class with the following definition, and I want it to have an override of Dispose method:

EDIT

it turns out there is a Dispose() method, but it's not an override. I was expecting an override. This may be an invalid question.... but why isn't it an override?

public class MyClient : IMyClient2
{
public void Dispose()
{
Dispose(true);
}

private void Dispose(bool disposing)
{
if(disposing)
{
Stop();
}
}
}


Where the interface it extends, and it's subsequent interface, are defined as:

public interface IMyClient2 : IMyClient
{
// one or two methods
}

public interface IMyClient : IDisposable
{
// a bunch of methods
}


I thought that implementing IDisposable would require that my class have the Dispose() override. But it doesn't and I don't know what I need to do to make it so that it does.

What do I need to do to be able to properly dispose of instances of my class?

Answer

If your class really implements these interfaces as in the question you should get a compilation error of

MyClass does not implement interface member IDisposable.Dispose()

enter image description here

Which will be solved the moment you add a public void Dispose() implementation


Update:

it turns out there is a Dispose() method, but it's not an override. I was expecting an override. This may be an invalid question.... but why isn't it an override?

override keyword is used when overriding an abstract or virtual method from a base class. When you are implementing an interface there is no need for the keyword. Stated by MSDN on the override keyword:

The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.

If instead of an interface you would extend a base class and the Dispose method would have an abstract or virtual keywords you could override it's implementation in the derived class.

See object's ToString() as an example:

public class Object
{       
    // Returns a String which represents the object instance.  The default
    // for an object is to return the fully qualified name of the class.
    // 
    public virtual String ToString()
    {
        return GetType().ToString();
    }    
}

And if in your class you will add a function of :

public override string ToString()
{
    // Add your implementation
}