Tuesday, 16 October 2012

What is the difference between new and override?

The differences between the two C# keywords is due to polymorphism. When a virtual method is called on a reference, the actual type of the object to which the reference refers is used to determine which method implementation should be used. When a method of a base class is overridden in a derived class (subclass), the version defined in the derived class is used. This is so even should the calling application be unaware that the object is an instance of the derived class.

The following example illustrates the override keyword:
public class BaseClass
{
    public virtual void AMethod()
    {
    }
}
 
public class DerivedClass : BaseClass
{
    public override void AMethod()
    {
    }
}
 
// ...
 
BaseClass baseClass = new DerivedClass();
baseClass.AMethod();

In the preceding example, DerivedClass.AMethod will be called; because, it overrides BaseClass.AMethod.

If the new keyword were used instead of the override keyword, then the method in the derived class would not override the base class method, but would hide it instead. The following is an example illustrating the new keyword:

public class BaseClass
{
    public virtual void AMethod()
    {
    }
}
 
public class DerivedClass : BaseClass
{
    public new void AMethod()
    {
    }
}
 
// ...
 
BaseClass baseClass = new DerivedClass();
baseClass.AMethod();
 
DerivedClass derivedClass = new DerivedClass();
derivedClass.AMethod();
 
The preceding example will call BaseClass.AMethod first, followed by DerivedClass.AMethod. Effectively, the two methods are unrelated except for the fact that they have the same name.

If neither the new nor overrides keyword is specified, the result is the same as if the new were specified. However, a compiler warning will be generated to ensure that the programmer is aware that a method in the base class is being hidden.
Post a Comment