Quantcast
Viewing all articles
Browse latest Browse all 10

Difference between ‘Shadowing’ and ‘Overriding’ (Shadowing vs Overriding) – C#

This is a very quick Tech-Tips..! Actually Shadowing is VB.Net concept, in C# this concept called hiding! We will see this chapter later. :)

Shadowing : Creating an entirely new method with the same signature as one in a base class.

Overriding: Redefining an existing method on a base class.

  • Both are used when a derived class inherits from a base class
  • Both redefine one or more of the base class elements in the derived class

If you want to read more regarding this, just follow this MSDN topic.

class A
 {
 public int M1()
 {
 return 1;
 }

 public virtual int M2()
 {
 return 1;
 }
 }

class B : A
 {
 public new int M1()
 {
 return 2;
 }

 public override int M2()
 {
 return 2;
 }
 }

class Program
 {
 static void Main(string[] args)
 {
 B b = new B();
 A a = (A)b;

 Console.WriteLine(a.M1()); //Base Method
 Console.WriteLine(a.M2()); //Override Method
 Console.WriteLine(b.M1());
 Console.WriteLine(b.M2());
 Console.Read();
 }
 }

The output is : 1, 2, 2, 2


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 10

Trending Articles