[Mono-list] Problem extending collection with generics

Jonathan Pryor jonpryor at vt.edu
Wed Jan 9 10:26:10 EST 2008


On Wed, 2008-01-09 at 09:35 -0500, Adam Tauno Williams wrote:
> > Also, when do I need to use the override keyword? It seems a little
> > redundant as it can only be used for methods that have been declared
> > virtual in the base class.
> 
> :) I've felt the same way SO many times.  I figure every language has to have at least one stupid thing.

It's not redundant, and it's not stupid.  The feature is for versioning
purposes.

Consider, Component v1:

	public class Component {
	  public void Foo () {}
	}

Then consumer v1:

	public class BarComponent : Component {
	  public void Bar () {}
	}

Everything is kosher.  But in Component v2, Component adds a new virtual
Bar method:

	// v2
	public class Component {
	  public void Foo () {}
	  public virtual int Bar () {return 0;}
	}

Without the `override' keyword, when you recompiled BarComponent you'd
either override a method that didn't exist when BarComponent was written
(if the return type matched, which they don't here), or you'd get a
compiler error (return type mismatch -- this is what Java does).

This is why in C# has the override keyword, so that when BarComponent
can explicitly specify that it's overriding a base class virtual method.
If it isn't (which is the default interpretation), the method will NOT
override the base virtual method of the same name.  However, a warning
will be produced, so the author of BarComponent v2 has a choice:
override the method with the override keyword, or hide Component.Bar()
with the new keyword:

	// v2
	public class BarComponent : Component {
	  public new void Bar () {}
	}

Java 5.0 attempts to fix this with the @Override annotation.  @Override
doesn't permit previously-compiling code to actually compile, but it
does check against spelling mistakes between the base and derived method
names (which C# override will also do).

So this is why C# has the override keyword.  It's not stupid, it's
required (unless you LIKE having the chance for previously compiling
code to start generating errors when all you did was update the base
class, OR you like having derived types silently overriding introduced
base method virtual methods with unknown semantics...).

As for why virtual/abstract methods require override and interface
implementations don't, it's because interfaces can't be changed (adding
a member to an interface is a breaking change, requiring that all
existing clients be rebuilt).  Consequently, there isn't a versioning
concern with interfaces.

 - Jon




More information about the Mono-list mailing list