07 October 2015

Shadowing in C#


  • In Method override  both methods (base & child class methods) have the same name, same number and same type of parameter in the same order with the same return type. The overridden base method must be virtual, abstract or override

  • but without these we can do using new keyword, this mechanism is called Shadowing

  • In the shadowing or method hiding, the child class has its own version of the function, the same function is also available in the base class.

  • Using this concept we can provide a new implementation for the base class method without overriding it.

  • Showing is used to protect against subsequent base class modification, We can change the access modifier

  • There is no control of a base class on shadowing

  • We can also use shadowing and method overriding together using the virtual and new keywords



public class BaseClass 
{
public string GetMethodOwnerName()
{
return "Base Class";
}
}
public class ChildClass : BaseClass
{
public new virtual string GetMethodOwnerName()
{
return "ChildClass";
}
}
public class SecondChild : ChildClass
{
public override string GetMethodOwnerName()
{
return "Second level Child";
}
}

static void Main(string[] args)
{
ChildClass c = new ChildClass();
Console.WriteLine(c.GetMethodOwnerName());
}


Output: ChildClass

We can't use the new and override keywords together. If you do then the compiler throws a compilation error

Shadowing  Example (using new keyword in child class method)

static void Main(string[] args) 
{
BaseClass c = new ChildClass();
Console.WriteLine(c.GetMethodOwnerName());
}


Output: Base Class