Information Technology Reference
In-Depth Information
This implementation reuse provides another benefit: If you add a method
to the base class, all derived classes are automatically and implicitly
enhanced. In that sense, base classes provide a way to extend the behavior
of several types efficiently over time: By adding and implementing func-
tionality in the base class, all derived classes immediately incorporate that
behavior. Adding a member to an interface breaks all the classes that
implement that interface. They will not contain the new method and will
no longer compile. Each implementer must update that type to include
the new member.
Choosing between an abstract base class and an interface is a question of
how best to support your abstractions over time. Interfaces are fixed: You
release an interface as a contract for a set of functionality that any type
can implement. Base classes can be extended over time. Those extensions
become part of every derived class.
The two models can be mixed to reuse implementation code while sup-
porting multiple interfaces. One obvious example in the .NET Framework
is the IEnumerable<T> interface and the System.Linq.Enumerable class.
The System.Linq.Enumerable class contains a large number of extension
methods defined on the System.Collections.Generic.IEnumerable<T>
interface. That separation enables very important benefits. Any class that
implements IEnumerable<T> appears to include all those extension meth-
ods. However, those additional methods are not formally defined in the
IEnumerable<T> interface. That means class developers do not need to
create their own implementation of all those methods.
Examine this class that implements IEnumerable<T> for weather
observations.
public enum Direction
{
North,
NorthEast,
East,
SouthEast,
South,
SouthWest,
West,
NorthWest
}
 
Search WWH ::




Custom Search