How function overriding is different in C# from Java?

If you are moving from Java to C#, than this is one thing which you would find very funny.

Suppose you wrote the following code:

class a
{
   public void display() 
   {
     Console.WriteLine("A");
   }
}

class b:a
{
   new public void display()
   {
    Console.WriteLine("B");
   } 
}

And did something like:

A a = new B();
a.display();

B b = new B();
b.display();

The output would be:
A
B

Although we expect here that as we have overriden display in B, so the display of B must be called. But this assumption is incorrect as we have reserved reference for A, so the C# compiler won't know that B can override display function. Hence we need to tell the compiler that there is a possibility that display can be overriden in derived classes and please check for it. To do so we would have to define the baseclass function which can be overriden as virtual and than use override keyword in all the derived classes. So that compiler can create a function pointer map or whatever it creates and point correct function pointer for various derived types.

This is done in the following way:


class a
{
   virtual public void display() 
   {
     Console.WriteLine("A");
   }
}

class b:a
{
   override public void display()
   {
    Console.WriteLine("B");
   } 
}

And did something like:

A a = new B();
a.display();

B b = new B();
b.display();

The output would be:
B
B

I hope this helps a few java developer to understand c#.
So, what i figured out from this is C# gives us a slight more flexibility for overriding a function with new but I am not yet sure will i like to use it? And if yes, a very good usecase for it.


Comments

Popular posts from this blog

Most expensive product on Amazon India By Category

8 Product Management lessons from the movie 'Gold'