New Keyword and Override Keyword with code example

 

In this article we have distinguished c-sharp override modifier and c-sharp new modifier and we also explained in detail use of override and new keyword using c# example step by step.

What is Method Overriding in C#?

We can achieve method overriding in c# by using an "override" keyword.

Method overriding means to override any virtual method of a base class with the same name, same signature but with different implementation in the derived class.

C# makes use of two keywords virtual and overrides to accomplish Method overriding.

If we want to re-implement any method with same name, same signature in derived classes (Parent - Child Relationship Inheritance) then in parent class we declare method with virtual keyword and again in the derived class we declare same method with same signature with override modifier. To provide different implementation or to extend implementation we do method overriding.

Virtual Method: A method with virtual keyword means it is going to be override in the further child classes to provide different implementation.

Example of Method Overriding using C-sharp

 

   public class Customer
    {

        /// 
        /// Normal Customers gets 5% of discount 
        /// 


        private double _discountrate = 0.05;

        public virtual void Discount(double amount)
        {
            double discountedbill = amount * _discountrate;
            double output = amount - discountedbill;
            Console.WriteLine("Discounted Bill :" + output);
        }


    }


    public class SpecialCustomers : Customer
    {

        /// 
        /// Special Customers gets 40% of discount 
        /// 
        private double _discountrate = 0.40;

        public override void Discount(double amount)
        {
            double discountedbill = amount * _discountrate;

            double output = amount - discountedbill;
            Console.WriteLine("Discounted Bill :" + output);

        }


    }

Output
 

    class Program
    {
        static void Main(string[] args)
        {
            Customer obj = new SpecialCustomers();
            obj.Discount(2000);
        }
    }


As you see from the above code that to display output we have used console application program. So in the main program we have created the object of a class and using that object we have called the "Discount" method. Output is shown below.

What is Method Hiding in C#?

We can achieve method hiding in c# by using a "new" keyword.

When a method is defined with "new" keyword is called as method hiding. It re-implements a method in derived class and hides the already existing method in base class or parent class.

Example of Method Hiding using C-sharp

 

 public class Customer
    {

        /// 
        /// Normal Customers gets 5% of discount 
        /// 


        private double _discountrate = 0.05;

        public void Discount(double amount)
        {
            double discountedbill = amount * _discountrate;
            double output = amount - discountedbill;
            Console.WriteLine("Discounted Bill :" + output);
        }


    }


    public class SpecialCustomers : Customer
    {

        /// 
        /// Special Customers gets 40% of discount 
        /// 
        private double _discountrate = 0.40;

        public new void Discount(double amount)
        {
            double discountedbill = amount * _discountrate;

            double output = amount - discountedbill;
            Console.WriteLine("Discounted Bill :" + output);

        }


    }

Let's suppose in the derived class if we use same method-name with same signature then during compilation it automatically shows an output error as "Use the new keyword if hiding is intended". So it is proved that in the derived class we cannot use same method-name with same signature. If we want to use then we need to use "new" keyword which hides the base class method and executes the derived class method.

Output 1
 

    class Program
    {
        static void Main(string[] args)
        {
            Customer obj = new SpecialCustomers();
            obj.Discount(2000);
        }
    }


Output 2
 

    class Program
    {
        static void Main(string[] args)
        {
            SpecialCustomers obj = new SpecialCustomers();
            obj.Discount(2000);
        }
    }


Difference between "Override" and "New" Modifier in C#

A method with "override" keyword is known as method overriding.

A method with "new" keyword is known as method hiding.

In method overriding a method overrides (Derived Class) already defined method in base class and we can add new implementation to it.

In method hiding or a method with "new" keyword in derived class hides the method of base class.

Normally we use "new" and "override" keywords in polymorphism scenario.

Combined Example of Method Overriding and Method Hiding using c#

In this example we will use both "override" and "new" keyword together in one single program.

 

public class Customer
    {

        private double _discountrate = 0.05;

        public virtual double CalculateDiscount(int TotalBill)
        {
            double discountedbill = TotalBill * _discountrate;

            return TotalBill - discountedbill;
        }

        public void PrintBill(int totalBill)
        {
            double bill = this.CalculateDiscount(totalBill);
            Console.WriteLine("Total Bill : " + bill + " @Disount of " + String.Format("Output Format For Percentage: {0:0%}", _discountrate));

        }

    }

    public class GoldCustomer : Customer
    {

        /// 
        /// 40% Discount for GoldCustomers
        /// 
        private double _discountrate = 0.40;

        public override double CalculateDiscount(int TotalBill)
        {
            double discountedbill = TotalBill * _discountrate;

            return TotalBill - discountedbill;
        }

        public new void PrintBill(int totalBill)
        {
            double bill = this.CalculateDiscount(totalBill);

            Console.WriteLine("Total Bill : " + bill + " @Disount of " + String.Format("Output Format For Percentage: {0:0%}", _discountrate));

        }



    }

    public class SilverCustomer : Customer
    {

        /// 
        /// 20% Discount for SilverCustomer
        /// 

        private double _discountrate = 0.20;

        public override double CalculateDiscount(int TotalBill)
        {
            double discountedbill = TotalBill * _discountrate;

            return TotalBill - discountedbill;
        }

        public new void PrintBill(int totalBill)
        {
            double bill = this.CalculateDiscount(totalBill);
            Console.WriteLine("Total Bill : " + bill + " @Disount of " + String.Format("Output Format For Percentage: {0:0%}", _discountrate));

        }
    }

    public class BronzeCustomer : Customer
    {
        /// 
        /// 10% Discount for BronzeCustomer
        /// 

        private double _discountrate = 0.10;
        public override double CalculateDiscount(int TotalBill)
        {
            double discountedbill = TotalBill * _discountrate;

            return TotalBill - discountedbill;
        }

        public new void PrintBill(int totalBill)
        {
            double bill = this.CalculateDiscount(totalBill);
            Console.WriteLine("Total Bill : " + bill + " @Disount of " + String.Format("Output Format For Percentage: {0:0%}", _discountrate));

        }
    }

Output
 

    class Program
    {
        static void Main(string[] args)
        {
            BronzeCustomer obj = new BronzeCustomer();
            obj.PrintBill(2000);
        }
    }

So hey friends this is all about method overriding and method hiding. If you like this article kindly share it with your friends on Facebook, Google+ and twitter. If you have any doubts, queries or suggesstions kindly tell @Gurunatha Dogi through your comments. He is there to solve your doubts, queries and understand your suggestion.

Guys if you have any suggestion for Onlinebuff.com improvement kindly please let me know through comments.

 

 

:: SHARE THIS POST ::

        
 

More C# Articles To Read Next:

 
Jun
06
2014

Understand params parameter with an example in C#?

CLICK TO READ FULL ARTICLE

Views - 12678 |Category - C#

Mar
24
2014

C# While Loop with an example using break and continue statements inside while loop

CLICK TO READ FULL ARTICLE

Views - 12268 |Category - C#

Mar
20
2014

How to deploy an assembly into GAC(Global Assembly Cache) ?

CLICK TO READ FULL ARTICLE

Views - 20497 |Category - C#

Mar
14
2014

Understanding concept of Concat,Substring methods of a string class ?

CLICK TO READ FULL ARTICLE

Views - 5526 |Category - C#

Mar
10
2014

C# if and nested if conditional statements with an example?

CLICK TO READ FULL ARTICLE

Views - 14858 |Category - C#

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

p1n51

 

 
Comments

Posted by Vishwajeet kumar on 2014-07-02

Very Well Explained Post. Thanks for clearing my doubts. Really Nice Post.

Posted by Basil Ntinga on 2014-06-16

Thank you