fxcop : Explicit method implementations in unsealed classes should provide alternate methods with protected accessibility
Well that is the formatted message of the following fxCop rule name ExplicitMethodImplementationsInUnsealedClassesHaveVisibleAlternates. Today I had this strange fxCop error that I really had to read about five times before I understood about 95% of the error. This error clearly needed some investigation instead of the usual refactoring with ReSharper (if you use VS2003 and fxCop then
ReFactor is definitaly a time saver!). The error I am talking about is "
Explicit method implementations in unsealed classes should provide alternate methods with protected accessibility". Which is a bigass name to begin with!
So lets read the extra information about this error:
Explicit method implementations are defined with private accessibility. Classes that derive from classes with explicit method implementations and choose to re-declare them on the class will not be able to call into the base class implementation unless the base class has provided an alternate method with appropriate accessibility.
When overriding a base class method that has been hidden by explicit interface implementation, in order to call into the base class implementation, a derived class must cast the base pointer to the relevant interface. When calling through this reference, however, the derived class implementation will actually be invoked, resulting in recursion and an eventual stack overflow.
The problem here was that I had a class implementing an interface method as follows.
A.
void ITest.SomeMethod() { ...}
The interface could also be implemented as the following alternative.
B.
public void SomeMethod() { ...}
In situation A you can't call ITest.SomeMethod from within your implementing object directly. The only way is to cast this to an ITest reference to call ITest.SomeMethod(). I knew that but I didn't need it because I would write the code as in situation B. ofcourse. Funny thing is that I forgot to seal to class and fxCop reminded me to do this with this error. But this means that you should normally just use situation B. as the primary way of implementating an interface. Problems arise when implementing two interfaces that share methods with the same signature but would have different implementations.
Normally I don't seal classes that often but I was working an a class that did some communication with unmanaged resources and had some unsafe code in it as well. It is a device driver wrapper and I wanted it sealed so people would think not twice but a hundred times before changing logic and would make the driver unstable by inheriting from it. We use
IOC a lot at the current project for external resources. Having someone around that change the driver factory configuration to supply a new driver because they would think they can easily add some functinality to it would not really make me a happy person.