Deciding on Virtual Members

You want to know when to make properties or methods virtual.

General rule: Don’t make a property or method virtual unless you’re sure of a scenario where derived classes must modify their behavior. Exception rule: Make public and protected members in non-sealed classes virtual unless you have a reason to make them sealed.

You may have noticed that these two rules contrast each other. They contrast because they reflect two different design approaches. The general rule places more design responsibility on the developer. It requires them to think about how inheritors could misuse base class members. The exception rule places more responsibility on inheritors but simplifies development. The recommendation is to favor the general rule. Spending more time designing an object hierarchy saves time later. Only adopt the exception rule when you’re unsure how inheritors will use the base class. Better performance is a secondary benefit of the general rule. Invoking a non-virtual or sealed member is faster than invoking a virtual one. Limit the number of virtual members to as few as possible.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s