HOME RESOURCES PLACEMENTS CONTACT FEEDBACK SUBSCRIBE
QUICK LINKS .NET Articles
.NET Training Tutorial
HR Interview Questions
.NET Interview Questions
SQL Interview Questions
JAVA Interview Questions

Difference between overriding and hiding a method
To clearly understand the difference between overriding and hiding a method, you must first understand polymorphism in C#. please read ploymorphism in C# article here.
Lets understand the difference with an example.

//Overriding a Method

using System;

public class Customer

{

    public virtual void CustomerType()

    {

        Console.WriteLine("I am a customer");

    }

}

 

public class CorporateCustomer : Customer

{

    public override void CustomerType()

    {

        Console.WriteLine("I am a corporate customer");

    }

 

}

public class PersonalCustomer : Customer

{

    public override void CustomerType()

    {

        Console.WriteLine("I am a personal customer");

    }

}

public class MainClass

{

    public static void Main()

    {

        Customer[] C = new Customer[3];

        C[0] = new CorporateCustomer();

        C[1] = new PersonalCustomer();

        C[2] = new Customer();

 

        foreach (Customer CustomerObject in C)

        {

            CustomerObject.CustomerType();

        }

    }

}



//Hiding a Method
using System;
public class Customer

{

    public virtual void CustomerType()

    {

        Console.WriteLine("I am a customer");

    }

}

//use the new operator to hide the base class method
public class CorporateCustomer : Customer

{

    public new void CustomerType()

    {

        Console.WriteLine("I am a corporate customer");

    }

 

}

public class PersonalCustomer : Customer

{

    public override void CustomerType()

    {

        Console.WriteLine("I am a personal customer");

    }

}

public class MainClass

{

    public static void Main()

    {

        Customer[] C = new Customer[3];

        C[0] = new CorporateCustomer();

        C[1] = new PersonalCustomer();

        C[2] = new Customer();

 

        foreach (Customer CustomerObject in C)

        {

            CustomerObject.CustomerType();

        }

    }

}

We override a method in C# using the override keyowrd. When we override a base class virtual method we are only changing the implementation of the method. The above example shows how to override a base class virtual method and use polymorphism to invoke the respective overriden method.

We hide a base class method using the new operator. When we hide a base class method, and use that class to participate in polymorphism then the base class virtual method is called during the runtime.

Njoy Programming
   ByPrasad Cherukuri