X hits on this document

829 views

0 shares

0 downloads

0 comments

237 / 396

C# LANGUAGE SPECIFICATION

class A { public void F() { Console.WriteLine("A.F"); }

public virtual void G() { Console.WriteLine("A.G"); } }

class B: A { new public void F() { Console.WriteLine("B.F"); }

public override void G() { Console.WriteLine("B.G"); } }

class Test { static void Main() { B b = new B(); A a = b; a.F(); b.F(); a.G(); b.G(); } }

In the example, A introduces a non-virtual method F and a virtual method G. The class B introduces a new non-virtual method F, thus hiding the inherited F, and also overrides the inherited method G. The example produces the output:

A.F B.F B.G B.G

Notice that the statement a.G() invokes B.G, not A.G. This is because the run-time type of the instance (which is B), not the compile-time type of the instance (which is A), determines the actual method implementation to invoke.

Because methods are allowed to hide inherited methods, it is possible for a class to contain several virtual methods with the same signature. This does not present an ambiguity problem, since all but the most derived method are hidden. In the example

using System;

class A { public virtual void F() { Console.WriteLine("A.F"); } }

class B: A { public override void F() { Console.WriteLine("B.F"); } }

class C: B { new public virtual void F() { Console.WriteLine("C.F"); } }

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

Document info
Document views829
Page views829
Page last viewedSun Dec 04 12:39:29 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments