13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>C#</strong> LANGUAGE SPECIFICATIONusing System;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 nonvirtualmethod F, thus hiding the inherited F, and also overrides the inherited method G. The example producesthe output:A.FB.FB.GB.GNotice that the statement a.G() invokes B.G, not A.G. This is because the run-time type of the instance (whichis B), not the compile-time type of the instance (which is A), determines the actual method implementation toinvoke. end example]Because methods are allowed to hide inherited methods, it is possible for a class to contain several virtualmethods with the same signature. This does not present an ambiguity problem, since all but the most derivedmethod are hidden. [Example: In the exampleusing 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"); }}class D: C{public override void F() { Console.WriteLine("D.F"); }}234

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

Saved successfully!

Ooh no, something went wrong!