Information Technology Reference
In-Depth Information
The recommendation to avoid using the new modifier to redefine nonvir-
tual functions should not be interpreted as a recommendation to make
everything virtual when you define base classes. A library designer makes
a contract when making a function virtual. You indicate that any derived
class is expected to change the implementation of virtual functions. The set
of virtual functions defines all behaviors that derived classes are expected
to change. The “virtual by default” design says that derived classes can
modify all the behavior of your class. It really says that you didn't think
through all the ramifications of which behaviors derived classes might
want to modify. Instead, spend the time to think through what methods
and properties are intended as polymorphic. Make those—and only
those—virtual. Don't think of it as restricting the users of your class.
Instead, think of it as providing guidance for the entry points you pro-
vided for customizing the behavior of your types.
There is one time, and one time only, when you want to use the new mod-
ifier. You add the new modifier to incorporate a new version of a base class
that contains a method name that you already use. You've already got code
that depends on the name of the method in your class. You might already
have other assemblies in the field that use this method. You've created the
following class in your library, using BaseWidget that is defined in another
library:
public class MyWidget : BaseWidget
{
public void NormalizeValues()
{
// details elided.
}
}
Yo u fi n i s h y o u r w i d g e t , a n d c u s t o m e r s a r e u s i n g i t . T h e n y o u fi n d t h a t t h e
BaseWidget company has released a new version. Eagerly awaiting new
features, you immediately purchase it and try to build your MyWidget
class. It fails because the BaseWidget folks have added their own Normal-
izeValues method:
public class BaseWidget
{
public void Normalizevalues()
{
 
Search WWH ::




Custom Search