Martin Ba Martin Ba - 1 year ago 90
C# Question

Can C# mark and check when a class implements interface methods?

When a base class contains a

method, to add a more derived version in a sub class, we have to use

AFAICT, this serves two purposes:

  • We don't accidentally overide a base method

  • If we mistype the method name when we want to override, we get an error (similar to Java, right?)

However, to my dismay it seems that (in VS2010 / .NET4) it is not possible to use
when implementing an interface method

Obviously the first bullet is rather a non issue, but the
keyword would have served as a good simple documentation and check that the interface methods are actually these that are marked as

So, when looking at a class implementation, is there any way other than a
// comment
to indicate that this method implements the method of a certain interface?

Answer Source

I believe that everything about your concern is summarized by this sentence:

but the overridekeyword would have served as a good simple documentation and check that the interface methods are actually these that are marked as override.

Think about what's an interface, and what's an implementer. A class may or may not implement an interface, and can still implement a method with the same signature as an interface. What an interface does is the job of ensuring that some class has the required members to fullfil a contract.

For example, a class Calculator may implement ICalculator and Calculator implements Addition(int, int). But Calculator couldn't implement ICalculator and it could perform an Addition(int, int) anyway.

How do you distinguish both cases? When to use override or not.

Another point: it's nice to implement a class, and fulfill an interface, and stop fulfilling it by just removing it from the class signature after the inheritance colon.

In the other hand, think that the documentation you're looking for is the compiler error telling you that Calculator implements interface ICalculator but it doesn't declare and implement one or more members defined by ICalculator. If the code compiles, you shouldn't care about if a member is of some or other interface. You know that some members are implementations of some interface, because your Calculator signature would look like this: public class Calculator : ICalculator.

Also, there's the case where a implementation member implements it to fulfill more than an interface. What's overriding your implementation? Isn't this more confusing than avoiding override keyword?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download