DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • DZone's Article Submission Guidelines
  • How to Submit a Post to DZone
  • Extending Java APIs: Add Missing Features Without the Hassle
  • Effortlessly Streamlining Test-Driven Development and CI Testing for Kafka Developers

Trending

  • DZone's Article Submission Guidelines
  • How to Submit a Post to DZone
  • Extending Java APIs: Add Missing Features Without the Hassle
  • Effortlessly Streamlining Test-Driven Development and CI Testing for Kafka Developers

All About Virtual, Override and New in C#

Jalpesh Vadgama user avatar by
Jalpesh Vadgama
·
Oct. 29, 13 · Interview
Like (0)
Save
Tweet
Share
10.30K Views

Join the DZone community and get the full member experience.

Join For Free

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..

csharp

Published at DZone with permission of Jalpesh Vadgama, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • DZone's Article Submission Guidelines
  • How to Submit a Post to DZone
  • Extending Java APIs: Add Missing Features Without the Hassle
  • Effortlessly Streamlining Test-Driven Development and CI Testing for Kafka Developers

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: