X hits on this document

977 views

0 shares

0 downloads

0 comments

239 / 396

C# LANGUAGE SPECIFICATION

An override declaration can access the overridden base method using a base-access (§‎7.5.8). In the example

class A { int x;

public virtual void PrintFields() { Console.WriteLine("x = {0}", x); } }

class B: A { int y;

public override void PrintFields() { base.PrintFields(); Console.WriteLine("y = {0}", y); } }

the base.PrintFields() invocation in B invokes the PrintFields method declared in A. A base-access disables the virtual invocation mechanism and simply treats the base method as a non-virtual method. Had the invocation in B been written ((A)this).PrintFields(), it would recursively invoke the PrintFields method declared in B, not the one declared in A, since PrintFields is virtual and the run-time type of ((A)this) is B.

Only by including an override modifier can a method override another method. In all other cases, a method with the same signature as an inherited method simply hides the inherited method. In the example

class A { public virtual void F() {} }

class B: A { public virtual void F() {}// Warning, hiding inherited F() }

the F method in B does not include an override modifier and therefore does not override the F method in A. Rather, the F method in B hides the method in A, and a warning is reported because the declaration does not include a new modifier.

In the example

class A { public virtual void F() {} }

class B: A { new private void F() {}// Hides A.F within B }

class C: B { public override void F() {}// Ok, overrides A.F }

226Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

Document info
Document views977
Page views977
Page last viewedThu Dec 08 23:14:04 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments