Information Technology Reference
In-Depth Information
object c = MakeObject();
// Call through MyClass reference:
MyClass cl = c as MyClass ;
cl.MagicMethod();
// Call through MyOtherClass reference:
MyOtherClass cl2 = c as MyOtherClass ;
cl2.MagicMethod();
When the new modifier is involved, that just isn't the case:
public class MyClass
{
public void MagicMethod()
{
// details elided.
}
}
public class MyOtherClass : MyClass
{
// Redefine MagicMethod for this class.
public new void MagicMethod()
{
// details elided
}
}
This kind of practice leads to a lot of developer confusion. If you call the
same function on the same object, you expect the same code to execute. The
fact that changing the reference, the label, that you use to call the function
changes the behavior feels very wrong. It's inconsistent. A MyOtherClass
object behaves differently in response to how you refer to it. The new mod-
ifier does not make a nonvirtual method into a virtual method after the fact.
Instead, it lets you add a different method in your class's naming scope.
Nonvirtual methods are statically bound. Any source code anywhere that
references MyClass.MagicMethod() calls exactly that function. Nothing in
the runtime looks for a different version defined in any derived classes.
Virtual functions, on the other hand, are dynamically bound. The runtime
invokes the proper function based on the runtime type of the object.
 
Search WWH ::




Custom Search