12.07.2015 Views

Accelerated

Accelerated

Accelerated

SHOW MORE
SHOW LESS
  • No tags were found...

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

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

CHAPTER 5 ■ INTERFACES AND CONTRACTS 137The first call, on b1, is obvious, as is the second call on c1. However, the third call, on b2, is notobvious at all. Since the A.Go method is not marked as virtual, the compiler generates code thatcalls A.Go. The fourth and final call is almost equally confusing, but not if you consider the fact thatthe CLR handles virtual calls on class type references and calls on interface references significantlydifferently. The generated IL for the fourth call makes a call to I.Go, which, in this case, boils downto a call to C.Go, since b2 is actually a C, and C reimplements I.You have to be careful when searching for the actual method that gets called, since you mustconsider whether the type of your reference is a class type or an interface type. The C# compilergenerates IL virtual method calls in order to call through to interfaces methods, and the CLR usesinterface tables internally to achieve this.■Note C++ programmers must realize that interface tables are different from C++ vtables. Each CLR type onlyhas one method table, whereas a C++ instance of a type may have multiple vtables.The contents of these interface tables are defined by the compiler using its method-matchingrules. For more detailed information regarding these interface tables, see Don Box and Chris Sells’Essential .NET, Volume I: The Common Language Runtime (Boston, MA: Addison-Wesley Professional,2002), as well as the CLI standard document itself.The C# method-matching rules explain the situation I discussed previously in the section“Interface Inheritance and Member Hiding.” Hiding a method in one hierarchical path of a diamond-shapedhierarchy hides the method in all inheritance paths. The rules state that when youwalk up the hierarchy, you short-circuit the search once you find a method at a particular level.These simple rules also explain how interface reimplementation can greatly affect the methodmatchingprocess, thus short-circuiting the compiler’s search during its progression up thehierarchy. Let’s consider an example of this in action:using System;public interface ISomeInterface{void SomeMethod();}public interface IAnotherInterface : ISomeInterface{void AnotherMethod();}public class SomeClass : IAnotherInterface{public void SomeMethod() {Console.WriteLine( "SomeClass.SomeMethod()" );}}public virtual void AnotherMethod() {Console.WriteLine( "SomeClass.AnotherMethod()" );}

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

Saved successfully!

Ooh no, something went wrong!