13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8 <strong>Language</strong> Overview// Author Bnamespace B{class Derived: A.Base}{}public virtual void F() {System.Console.WriteLine("Derived.F");}So far, so good, but now the versioning trouble begins. The author of Base produces a new version, giving itits own method F.// Author Anamespace A{public class Base // version 2}{}public virtual void F() { // added in version 2System.Console.WriteLine("Base.F");}This new version of Base should be both source and binary compatible with the initial version. (If it weren’tpossible to simply add a method then a base class could never evolve.) Unfortunately, the new F in Basemakes the meaning of Derived’s F unclear. Did Derived mean to override Base’s F? This seems unlikely,since when Derived was compiled, Base did not even have an F! Further, if Derived’s F does overrideBase’s F, then it must adhere to the contract specified by Base—a contract that was unspecified whenDerived was written. In some cases, this is impossible. For example, Base’s F might require that overridesof it always call the base. Derived’s F could not possibly adhere to such a contract.<strong>C#</strong> addresses this versioning problem by requiring developers to state their intent clearly. In the originalcode example, the code was clear, since Base did not even have an F. Clearly, Derived’s F is intended as anew method rather than an override of a base method, since no base method named F exists.If Base adds an F and ships a new version, then the intent of a binary version of Derived is still clear—Derived’s F is semantically unrelated, and should not be treated as an override.However, when Derived is recompiled, the meaning is unclear—the author of Derived may intend its F tooverride Base’s F, or to hide it. Since the intent is unclear, the compiler produces a warning, and by defaultmakes Derived’s F hide Base’s F. This course of action duplicates the semantics for the case in whichDerived is not recompiled. The warning that is generated alerts Derived’s author to the presence of theF method in Base.If Derived’s F is semantically unrelated to Base’s F, then Derived’s author can express this intent—and,in effect, turn off the warning—by using the new keyword in the declaration of F.// Author Anamespace A{public class Base // version 2}{}public virtual void F() { // added in version 2System.Console.WriteLine("Base.F");}47

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!