Shadowing hides a method in a base class.
We can achieve shadowing in C# using new keyword .
- If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class.
- If the new keyword is not specified in the derived class , the compiler will issue a warning and the method in the derived class will hide the method in the base class.
public class clsA { public void Foo() { Console.WriteLine("This is Base class A"); } public virtual void Bar() { Console.WriteLine("This is Base class A with virtual"); } public virtual void ss(){Console.WriteLine("Hiiiiiiiiiiiiiii");} } class clsB : clsA { public new void Foo() { Console.WriteLine("This is Child Class B"); } public override void Bar() { Console.WriteLine("this is Child class B override"); } public new void ss() { Console.WriteLine("Byeeeeeeeeeeeeeeee"); } } class Program { static void Main(string[] args) { clsA obj = new clsA(); obj.Foo(); obj.Bar(); obj.ss(); clsB obj1 = new clsB(); obj1.Foo(); obj1.Bar(); obj1.ss(); clsA obj2 = new clsB(); obj2.Foo(); obj2.Bar(); obj2.ss(); Console.ReadLine(); } } /* if you don't use new key word in Child class B then compiler shows an warning that for hiding use new keyword. By using New keyword it hides the base class method this is called Shadowing. use static keyword in Base and Derived classes and check once... Comment the method Bar() in derived class B and check it once...*/ Output: This is Base class A This is Base class A with virtual Hiiiiiiiiiiiiiii This is Child Class B this is Child class B override Byeeeeeeeeeeeeeeee This is Base class A this is Child class B override Hiiiiiiiiiiiiiii |
No comments:
Post a Comment