What do you mean by shadowing in .NET?Assume that
you have a class that derives from the base class and redefines a method
in the base class. Then what process is happening? You will generally
assume it as overriding meaning that derived class method overrides base
class method and redefines the method.
Even when it redefines, the derived class method should have the same signature as base class method and the derived class method should include the keyword override in its method signature. What if you dont explicitly specify the override keyword in your derived class method? Even then does it mean as overriding. No, if you dont explicitly use override then the derived class method is shadowing base class method. This means that derived class is creating a new method that is no way related to the base class method. But the derived class method completely shadows/hides base class method. Unlike overriding, members sharing same name in derived class can have a totally different signature since it is a new member. Shadowing
happens by default when two members share the same name but override keyword
is not mentioned. However you can explicitly perform shadowing using a
keyword. Given below are examples to demonstrate shadowing in both the languages. Shadowing
in C#: In this example, derived class has completely shadowed member and displayMsg of baseClass. Note that the signature of member and displayMsg is different in derivedClass when compared to baseClass. This is acceptable in case of shadowing. But in overriding, it will throw error. Shadowing
in VB.NET: Public Class
derivedClass Module testModule The MessageBox will display 100 first and then Hello. Invoking
Base Class Member Using Derived Class Object: Now to your surprise, you will get the output as 100. This is because you create a reference to baseClass which is assigned with derivedClass object. Whatever is the assigned object, the reference takes priority and the baseClass member gets displayed. In this case, shadowing is suppressed.
|