- The interface implementation relationship is a “can do” relationship: The class can do what the interface requires.
- The interface defines the contract between the classes that implement the interface and the classes that use the interface.
Interface Implementation
- Declaring a class to implement an interface is similar to deriving from a base class.
- The only difference is that classes can implement multiple interfaces.
public class Contact : PdaItem, IListable, IComparable
- Interfaces can never be instantiated; and therefore, interfaces cannot have constructors or finalizers.
- Interface instances are available only from types that implement them.
- Interfaces cannot include static members.
- It is not possible to use the abstract modifier on interface members explicitly.
- Extension methods work with interfaces in addition to classes.
Implicit Member Implementation
- With implicit member implementation, you access the interface methods and properties as if they were part of the class.
public class Test : ITest
{
public string Id => "Implicit";
}
- Implicit member implementation doesn’t require a cast because the member is not hidden from direct invocation on the implementing class.
- Implicit member implementations must be public.
virtual is optional depending on whether derived classes may override the implementation.
- Eliminating
virtual will cause the member to behave as though it is sealed.
override is not allowed because the interface declaration of the member does not include implementation, so override is not meaningful.
Explicit Member Implementation
- Explicitly implemented methods are available only by calling through the interface itself.
- This is typically achieved by casting an object to the interface.