3.10. Overriding the Inherited Virtual Interface

A derived class can either inherit or override the virtual interface of its base class. To inherit a member, the class need do nothing. Inheritance is the default behavior. To override an inherited abstract or virtual member, however, we must label the definition with the override keyword. Otherwise the compiler treats the instance as an independent definition reusing the name of the inherited member. If you do this—accidentally or not—you'll receive a warning from the compiler. If the warning is spurious, you can turn it off by specifying the new keyword; we see how to do this in Section 3.12.

Both the base-class and derived-class instances of the virtual function must have the same access level, as well as the same signature and return type.[3] For example, the following does not represent a legal override because the derived-class instance has a ref string parameter, which requires a different calling syntax:

[3] C# does not support covariance of the return type. That is, if a base-class virtual function returns an object of the base class, the derived-class instance must do so as well. The derived-class instance may not declare itself to return a derived-class object.

public class Base
{
   public virtual void display( string msg ) { ... }
}

public class Derived : Base
{
   // error: signatures differ by ref keyword
   public override void display( ref string msg ){ ... }
}

The Derived class instance of display() results in a compile-time error because the override keyword instructs the compiler to look for the matching inherited instance, and it cannot find one.

When we override a property, we must specify the same property type and provide one or both of the accessors specified by the inherited property. The same holds true of an indexer, with the added requirement that the type and number of indices match as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.11.247