Common Type System—New Slots


Jump to: navigation, search
Visual C# Tutorials
.NET Framework Tutorials

Common Type System

© 2006 Wiley Publishing Inc.

New Slots

Methods can also be marked as newslot rather than override, meaning that they introduce an entirely new version of a method and explicitly do not provide a new version of a base type’s implementation. newslot is used even when a base type implementation doesn’t exist, preventing versioning problems from arising.

This is indicated with the new keyword in C#. For example, using the above example as a basis:

class Base
{
   public virtual void Foo()
   {
      Console.WriteLine("Base::Foo");
   }
}
 
class Derived : Base
{
   public new void Foo()
   {
      Console.WriteLine("Derived::Foo");
   }
}

The behavior of the sample code changes ever so slightly:

// Construct a bunch of instances:
Base base = new Base();
Derived derived = new Derived();
Base derivedTypedAsBase = new Derived();
 
// Now invoke Foo on each of them:
base.Foo();
derived.Foo();
derivedTypedAsBase.Foo();

Executing the above code prints out:

Base::Foo
Derived::Foo
Base::Foo

Notice that the first two method calls work as expected. There is a subtle difference, however. In the original virtual method and overriding example, the IL contained callvirt instructions to the Base::Foo method. In this case, however, there is a single callvirt to Base::Foo, followed by an ordinary call to Derived::Foo, an entirely different method.

Then a possible surprise arises: the third invocation results in "Base::Foo". This is because the method call against the Base-typed reference pointing to a Derived instance will emit a virtual call to the method Base::Foo. The virtual method at runtime will notice that Base’s version of Foo has not been overridden; instead, the Derived::Foo method is represented as an entirely distinct method with its own slot in the method table. Thus, the method dispatch calls Base’s version.


Previous_Page_.gif Next_Page_.gif





Personal tools