1

I am using a third party class library. This implements class A that implements IDisposable and an interface B that also implements IDisposable.

I have a class that needs to inherit from class A and implemnt interface B. If a do a Visual Studio code analysis it reports that I am not implementing IDisposable correctly and to remove IDisposable from the list of interfaces.

Given that I cannot change A or B and the fact they both need to handle IDisposable. Is there a recommended way of handling this or doing I just ignore this.

External library has:

public interface IModbusMaster : IDisposable

public abstract class ModbusDevice : IDisposable

My code uses:

public abstract class ModbusMaster : ModbusDevice, IModbusMaster

Thanks

3 Answers3

2

Found a similar question here, implies a false positive that can be suppressed.

Code Analysis CA1063 fires when deriving from IDisposable and providing implementation in base class

Community
  • 1
  • 1
0

You cannot inherit from multiple classes in C# so you have to code your way around this with a Delegation Pattern.

You should inherit from A (is-a) and "have" (has-a) instance of B:

class MyClass extends A
{
    private B instance_of_b;

    public MyClass(B instance_of_b) // constructor
    {
        this.instance_of_b = instance_of_b;
        ...

Your methods from B are then delegated to the instance of b:

    public double MethodInB(int arg1, string arg2)
    {
        return instance_of_b.MethodInB(arg1, arg2);
    }

This is the only chance you get to mix behaviour of more than one class and mimic multi-inheritance.

Obviously, this comes with a lot of other synchronization and management problems you'll have to tackle.

pid
  • 11,472
  • 6
  • 34
  • 63
0

If A is a class, and it implements IDisposable, it must provide a Dispose method. It can however provide an abstract definition (if the class itself is marked as abstract), which means that you must override that Dispose method when you inherit from that class:

public abstract class BaseClassFromLibrary : IDisposable
{
    public abstract void Dispose();
}

public class MyClass : BaseClassFromLibrary
{
    public override void Dispose()
    {
    }
}
sondergard
  • 3,184
  • 1
  • 16
  • 25