Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override explicitly implemented interface method in derived class

I want to explicitly implement an interface method on a base class.

Beyond this, I wanted to make this method virtual so I could override it on a derived class, but explicitly implemented methods do not allow this.

I have tried making a protected virtual method in the base, calling this from the interface method, and then overriding this method in the derived class. This seems to work but FxCop is complaining with rule CA1033 "Interface methods should be callable by child types".

(My base class implements the interface, the derived class does not.)

How should I improve this (abbreviated) code to be more correct, or should I just ignore FxCop in this case?

In the base class:

protected virtual string ConstructSignal()
{
    return "Base string";
}

#region ISignal Members

string ISignal.GetMessage()
{
    this.ConstructSignal();
}

#endregion

In the derived class:

protected override string ConstructSignal()
{
    return "Derived string";
}

Decided to implement the interface methods implicitly in the end, which still works and keeps FxCop happy.

like image 884
Andy Avatar asked Nov 06 '22 11:11

Andy


1 Answers

Move ConstructSignal() method declaration to some interface (lets name it IConstructSignal) and implement it in derived class. Following explicit implementation will work:

string ISignal.GetMessage()
{
    (this as IConstructSignal).ConstructSignal(); // implementation of derived class called
}
like image 120
Sergei Krivonos Avatar answered Nov 14 '22 21:11

Sergei Krivonos