Sunday, October 27, 2013

All about Virtual,Override and New in C#


I have seen that lots of people get confused with Virtual, Override and new keyword in C#. So I thought it will be a good idea to write a blog post about it. In this blog post we will learn what is virtual, override and new keyword in C# and what’s difference between override and new in C#.

Virtual and Override in C#:


Virtual keyword allows class member to override in derived class. Let’s take simple example. I have class A which contains Print Method method as virtual method and I have another class B which is derived from class A which overrides Print method. Following is a code for that.

public class A
{
    public virtual void Print()
    {
        System.Console.WriteLine("Virtual Print method from a");
    }
}

public class B:A
{
    public override void Print()
    {
        System.Console.WriteLine("Override Print method from b");
    }
}
Now If I create a object of class A like following and run the code Print method run as normal method. Following is code for for that.
class Program
   {
       static void Main(string[] args)
       {
          A a=new A();
          a.Print();
       }
   }

Once you run this it will have following output.

VirutalAsNormalMethodinCsharp

But when you create a object of class B like following it will completely override the functionality of class A. That is called method Method Overriding. Following is a code for that.

class Program
{
    static void Main(string[] args)
    {
       B b=new B();
       b.Print();
    }
}

Now, if you run this code it will completely override the code and following will be output as expected.

OverrideMethodinCsharp

How to call base class method with override:


In some scenario, we need base class functionality also while overriding the method of that class. C# provides that functionality with ‘base’ keyword. For that I have changed code of class B like following.
public class B:A
{
public override void Print()
{
    System.Console.WriteLine("Override Print method from b");
    base.Print();
}
}

class Program
{
    static void Main(string[] args)
    {
       B b=new B();
       b.Print();
    }
}

Now if you run the code you will see output of both method as expected.

BaseKeywordwithoverridecsharp

What is difference between new and override in C#:


After looking into above example some people will argue that this functionality will be achieved by new keyword also. This is call Method Hiding where with new keyword you can hide functionality of base class.  But wait there is a difference. Both are slightly different let’s take some simple example to show difference following is a code for that.
namespace Oops
{
    class Program
    {
        static void Main(string[] args)
        {
           A a=new B();
           B b=new B();

           a.Print();
           b.Print();
        }
    }

    public class A
    {
        public virtual void Print()
        {
            System.Console.WriteLine("Virtual Print method from a");
        }
    }

    public class B:A
    {
        public override void Print()
        {
            System.Console.WriteLine("Override Print method from b");
        }
    }
}

In this code, same A class Print method is override by B class Print method and I have created two object of class B. One with reference to base class A and another B itself. Now let’s run this example and following is a output.

OverridewithInheritancedifferencebetweenoverideandnew

Here you see both time it will override class A’s Print Method. Now let’s change above code with new keyword like following.
namespace Oops
{
    class Program
    {
        static void Main(string[] args)
        {
           A a=new B();
           B b=new B();

           a.Print();
           b.Print();
        }
    }

    public class A
    {
        public virtual void Print()
        {
            System.Console.WriteLine("Virtual Print method from a");
        }
    }

    public class B:A
    {
        public new void Print()
        {
            System.Console.WriteLine("Override Print method from b");
        }
    }
}

Now you run this code. Following is output.

OverridewithInheritanceDifferenceBetweenoverrideandnew

If you see both output carefully then you will notice a difference. With override keyword it will override Print method in both scenarios. While with new keyword it will only hide print method and both method exist as separate method so if you create a class A object with B then it will class A’s Print method without hiding it and If you create class B object with B then it will hide the base class method and print from class B’s method. So that was the difference.

That’s it. Hope you like it. Stay tuned for more..
Share:

6 comments:

  1. hope they included also in the 'express' versions so individual developers can make use of these features too.

    ReplyDelete
  2. But it's not included right now :(

    ReplyDelete
  3. are you really sure with your reply? if yes, can you tell me how to enable it in the express editions? thanks.

    ReplyDelete
  4. I define virtual method as "When virtual method is used, the method resolution is based on the run-time type of the object whereas normally it is compile time type of object" However nice to learn exception to this statement by Method Hiding using "new" keyword.

    ReplyDelete

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews