Matt's Mind

Friday, July 16, 2004

C# and virtual methods

Continuing my ramblings on C#'s default to non-polymorphic (non-virtual) methods, I've been revisiting an excellent series of interviews at artima.com with Anders Hejlsberg, daddy of C#. One quote is of particular interest:

Bill Venners: In Java, instance methods are virtual by default—they can be overridden in subclasses unless they are explicitly declared final. In C#, by contrast, instance methods are non-virtual by default. To make a method virtual, the programmer must explicitly declare it virtual. Why is non-virtual the default in C#?

Anders Hejlsberg: There are several reasons. One is performance. We can observe that as people write code in Java, they forget to mark their methods final. Therefore, those methods are virtual. Because they're virtual, they don't perform as well. There's just performance overhead associated with being a virtual method. That's one issue.

This is a very telling statement because (a) it's wrong - it's not a performance issue in Java and (b) because it's not consistent with another key C# design decision. Java classes are JIT'ed at runtime when information about subclassing and method overrides is known, so that JIT can easily auto-"final" methods and classes. The only reason for the programmer to use final is to ensure safety API-wise.

The inconsistency is that, if methods are "sealed" by default to make API contracts safer, why aren't classes also sealed by default? I think the real reason is that C# required sealed methods in order to not suck when linking against precompiled classes (eg the entire .NET standard framework), but sealed classes wouldn't have made much difference. If Anders actually believed what he was saying about sealed methods in API contracts, then it would apply to classes too.

I think the real reason for these design decisions in C# is that this is the same default as C++, a language whose author unabashedly admits major design decisions were driven by performance, not safety.

0 Comments:

Post a Comment

<< Home