Hi, in short, I’d like to describe why using method shadowing in a project can be dangerous.

First, let’s have a short introduction to what method overriding and shadowing is.

Overriding – it’s changing the method body. What’s important is that the method signature is resolved at runtime based on the object’s type. The base method has to be declared with ‘virtual’ modifier.

Shadowing – it’s changing the method body. It’s early bound, thus resolved at compile type based on the object’s type. The base method doesn’t have to have any special modifier. However, in the derived class, the shadowing method can optionally include ‘new’ modifier (it’s not necessary, but without it compilers generate a warning).

Ok, basically in both cases the methods, which are used for overriding/shadowing have to have identical signatures. Additionally, in shadowing we can change the access level and mark the new method as virtual. 

Two cents

So what’s the main difference in terms of usage? Well, the good thing about method overriding is that it requires a modifier during the class declaration, which ensures that the developer, who is responsible for it, makes the educated decision (hopefully) and that the modifier is there for a reason.

The problem with shadowing is that it can be used to hide any method while completely changing its behavior in the derived class. Thus one may wonder what’s happening only to find that a method that wasn’t supposed to be modified, was shadowed.

There’s also one extra feature to shadowing. Due to the difference in time of binding, strange (or even stranger) things may occur when casting the object from one class to another.

Let’s have a look at an example:

class Base
{
  public void func1()
  {
    Console.WriteLine("I'm not afraid of death; I just don't want to be there when it happens.");
  }

  public virtual void func2()
  {
    Console.WriteLine("I don't know the question, but sex is definitely the answer.");
  }
}

class Shadowed : Base
{
  public new void func1()
  {
    Console.WriteLine("Life doesn't imitate art, it imitates bad television.");
  }

  public override void func2()
  {
    Console.WriteLine("I'm not anti-social. I'm just not social.");
  }
}

Then in the main method we executes both method on objects:

var obj1 = new Base();
obj1.func1();
obj1.func2();
var shadowed = new Shadowed();
shadowed.func1();
shadowed.func2();

Base basedFromShadow = shadowed;
basedFromShadow.func1(); // early binding
basedFromShadow.func2(); // late binding

Console.ReadLine();

Here’s the output:

When a method is overridden, compiler knows about it and thus points to the overridden method from the derived class. However, when a method is hidden/shadowed there’s no such knowledge. Therefore, the func2 of the upcasted class is called, which sometimes can lead to unexpected behavior.

There are currently no comments.

This site uses Akismet to reduce spam. Learn how your comment data is processed.