Click here to Skip to main content
15,881,281 members
Articles / Programming Languages / C#

Virtual vs Override vs New Keyword in C#

Rate me:
Please Sign up or sign in to vote.
4.52/5 (59 votes)
8 Sep 2014CPOL3 min read 261.4K   73   18
Virtual vs Override vs New Keywords in C#

Introduction

The purpose of writing this article is simple, which is- a simple and fresh demonstration of basic difference between these three mostly used and confusing keywords in C# with some reference example. This article is purely for the beginner in C#.

Outline

  • Overview
  • Introduction
    • Virtual Keyword
    • Override Keyword
    • New Keyword
  • Demo Examples
    • Sample Implementation
    • New Keyword
    • Virtual & Override Keyword
    • Method Overloading + Riding
  • Key Points
  • Conclusions

Overview

In this article, I’ll explain how virtual, override and new keywords are different from each other by taking some set of examples respectively (some sort of functionality).

At the end, there will be some key points to remember about all these 3 keywords.

Introduction

In this introductory part, I am going to give a brief introduction of all these 3 keywords. So here they are:

Virtual Keyword

Virtual keyword is used for generating a virtual path for its derived classes on implementing method overriding. Virtual keyword is used within a set with override keyword. It is used as:

C#
// Base Class
    class A
    {
        public virtual void show()
        {
            Console.WriteLine("Hello: Base Class!");
            Console.ReadLine();
        }
    }

Override Keyword

Override keyword is used in the derived class of the base class in order to override the base class method. Override keyword is used with virtual keyword, as:

C#
// Base Class
    class A
    {
        public virtual void show()
        {
            Console.WriteLine("Hello: Base Class!");
            Console.ReadLine();
        }
    }

// Derived Class

    class B : A
    {
        public override void show()
        {
            Console.WriteLine("Hello: Derived Class!");
            Console.ReadLine();
        }
    }

New Keyword

New keyword is also used in polymorphism concept, but in the case of method overloading So what does overloading means, in simple words we can say procedure of hiding your base class through your derived class.

It is implemented as:

C#
class A
    {
        public void show()
        {
            Console.WriteLine("Hello: Base Class!");
            Console.ReadLine();
        }
    }

    class B : A
    {
        public new void show()
        {
            Console.WriteLine("Hello: Derived Class!");
            Console.ReadLine();
        }
    }

Demo Example

Sample Implementation

Here’s a simple implementation in C# without using any keyword. Do you think it will run fine or show some RUN or COMPILE time errors?

Let’s see:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Generics
{
    class A
    {
        public void show()
        {
            Console.WriteLine("Hello: Base Class!");
            Console.ReadLine();
        }
    }

    class B : A
    {
        public void show()
        {
            Console.WriteLine("Hello: Derived Class!");
            Console.ReadLine();
        }
    }

    class Polymorphism
    {
        public static void Main()
        {
            A a1 = new A();
            a1.show();
            B b1 = new B();
            b1.show(); 
            A a2 = new B();
            a2.show();

        }
    }
}

Output Window

Image 1

It is showing some sort of output which means there is neither run time nor compile time error. But it will definitely show a Warning to you in your Visual Studio. So what is it and how to remove it. Do you want to know?

Keep reading and you will go through that.

Warning Message

Here’s a warning message that you will get:

Image 2

Solution

The solution of this problem is already in the warning. Just read it carefully and you will get that. Yes, you got that right, for removing that warning we need to use NEW keyword.

In the next sample, the demo example shows you a simple demo snippet and implementation of new keyword.

(I hope now you get why we are using new keyword in here.)

New Keyword | Method Overloading

Here’s a simple snippet of method overloading mechanism. So just go through it and guess the output:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Generics
{
    class A
    {
        public void show()
        {
            Console.WriteLine("Hello: Base Class!");
            Console.ReadLine();
        }
    }

    class B : A
    {
        public new void show()
        {
            Console.WriteLine("Hello: Derived Class!");
            Console.ReadLine();
        }
    }

    class Polymorphism
    {
        public static void Main()
        {
            A a1 = new A();
            a1.show();
            B b1 = new B();
            b1.show(); 
            A a2 = new B();
            a2.show();

        }
    }
}

Output Window

Image 3

Explanation

The procedure goes something like this:
(using overhiding as a ref for overloading)

Image 4

Virtual & Override Keywords | Method Overriding

This is a simple example of method overriding. Just go through it and guess the output again and also try to differentiate between the previous snippet and this snippet.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Generics
{
    class A
    {
        public virtual void show()
        {
            Console.WriteLine("Hello: Base Class!");
            Console.ReadLine();
        }
    }

    class B : A
    {
        public override void show()
        {
            Console.WriteLine("Hello: Derived Class!");
            Console.ReadLine();
        }
    }

    class Polymorphism
    {
        public static void Main()
        {
            A a1 = new A();
            a1.show();
            B b1 = new B();
            b1.show();
            A a2 = new B();
            a2.show();
        }
    }
}

Output Window

Image 5

Explanation

The flow goes something like this:

Image 6

Overriding + Hiding | Together

In this snippet, I show how both these methods can work together in the same snippet. So just go through this and guess the output.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Generics
{
    class A
    {
        public virtual void show()
        {
            Console.WriteLine("Hello: Base Class!");
            Console.ReadLine();
        }
    }

    class B : A
    {
        public override void show()
        {
            Console.WriteLine("Hello: Derived Class!");
            Console.ReadLine();
        }
    }

    class C : B
    {
        public new void show()
        {
            Console.WriteLine("Am Here!");
            Console.ReadLine();
        }
    }

    class Polymorphism
    {
        public static void Main()
        {
            A a1 = new A();
            a1.show();
            B b1 = new B();
            b1.show();
            C c1 = new C();
            c1.show();
            A a2 = new B();
            a2.show();
            A a3 = new C();
            a3.show();
            B b3 = new C();
            b3.show();
        }
    }
}

Output Window

Image 7

Explanation

The flow goes something like this:

(using overhiding as a ref for overloading)

Image 8

Key Points

I am giving some key points about these keywords by taking reference of method overloading and overriding concepts, as these keywords are used in these mechanism.

Virtual & Override

  • Used in polymorphism implementation
  • Includes same method name and same params’
  • Used in method overriding concept
  • It is also called run time polymorphism
  • Causes late binding

New

  • It is also used in polymorphism concept
  • Includes same method name and different params’
  • Used in method overloading concept
  • It is compile time polymorphism
  • Cause early binding

Conclusion

So did you like it, I hope you did!

Well, I tried to give just a brief sketch of these keywords, which are very necessary for a beginner in C# as well as in OOPS. If you have a good handle of OOPs concept, then you can take any object oriented language in your pocket.

So just go through OOPs first and then C# and if you are facing any problem, then feel free to ping or message me.

Happy coding!

Cheers!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
Geek | Blogger | Data Science Scholar | TechSavvy | Developer | Painter | Author | Trainer | Tech Evangelist | Philanthropist

Comments and Discussions

 
QuestionVirual Methods Pin
Member 1179666625-Jul-16 22:05
Member 1179666625-Jul-16 22:05 
Questionoutput Pin
Member 1165637910-Feb-16 21:45
Member 1165637910-Feb-16 21:45 
AnswerRe: output Pin
Member 1201687716-Jun-16 0:49
Member 1201687716-Jun-16 0:49 
GeneralMy vote of 2 Pin
Member 1165637910-Feb-16 21:42
Member 1165637910-Feb-16 21:42 
GeneralMy vote of 5 Pin
Ivandro Ismael8-Aug-15 16:33
Ivandro Ismael8-Aug-15 16:33 
GeneralMy vote of 4 Pin
Ujjval Shukla6-Jun-15 19:25
Ujjval Shukla6-Jun-15 19:25 
NewsCode Pin
Member 1145043913-Feb-15 5:14
Member 1145043913-Feb-15 5:14 
GeneralRe: Code Pin
Abhishek Jaiswall18-Feb-15 0:44
Abhishek Jaiswall18-Feb-15 0:44 
Suggestion[My vote of 2] Missing some very important points Pin
Assorted Trailmix9-Sep-14 17:39
Assorted Trailmix9-Sep-14 17:39 
GeneralRe: [My vote of 2] Missing some very important points Pin
Abhishek Jaiswall10-Sep-14 6:46
Abhishek Jaiswall10-Sep-14 6:46 
GeneralNice one. Pin
Sandeep Singh Shekhawat8-Sep-14 20:57
professionalSandeep Singh Shekhawat8-Sep-14 20:57 
GeneralRe: Nice one. Pin
Abhishek Jaiswall9-Sep-14 6:02
Abhishek Jaiswall9-Sep-14 6:02 
Questionoverhiding? PinPopular
Paulo Zemek8-Sep-14 4:54
mvaPaulo Zemek8-Sep-14 4:54 
SuggestionRe: overhiding? Pin
Sam Hobbs9-Sep-14 6:16
Sam Hobbs9-Sep-14 6:16 
Paulo, I totally agree that overhiding sounds like an error. I very much agree that there's no "over" there. Use of "over" in "overhiding" sure seems wrong to me.
AnswerRe: overhiding? Pin
User 592419-Sep-14 13:59
User 592419-Sep-14 13:59 
AnswerRe: overhiding? Pin
Hatredalper25-Jun-15 22:36
Hatredalper25-Jun-15 22:36 
GeneralMy vote of 5 Pin
Anurag Gandhi8-Sep-14 4:41
professionalAnurag Gandhi8-Sep-14 4:41 
GeneralRe: My vote of 5 Pin
Abhishek Jaiswall8-Sep-14 5:53
Abhishek Jaiswall8-Sep-14 5:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.