Click here to Skip to main content
13,191,400 members (71,366 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

183.1K views
70 bookmarked
Posted 8 Sep 2014

Virtual vs Override vs New Keyword in C#

, 8 Sep 2014
Rate this:
Please Sign up or sign in to vote.
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:

// 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:

// 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:

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:

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

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:

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:

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

Explanation

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

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.

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

Explanation

The flow goes something like this:

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.

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

Explanation

The flow goes something like this:

(using overhiding as a ref for overloading)

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)

Share

About the Author

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

You may also be interested in...

Comments and Discussions

 
QuestionVirual Methods Pin
Member 1179666625-Jul-16 22:05
memberMember 1179666625-Jul-16 22:05 
Questionoutput Pin
Member 1165637910-Feb-16 21:45
memberMember 1165637910-Feb-16 21:45 
AnswerRe: output Pin
Member 1201687716-Jun-16 0:49
memberMember 1201687716-Jun-16 0:49 
GeneralMy vote of 2 Pin
Member 1165637910-Feb-16 21:42
memberMember 1165637910-Feb-16 21:42 
GeneralMy vote of 5 Pin
Ivandro Ismael8-Aug-15 16:33
memberIvandro Ismael8-Aug-15 16:33 
GeneralMy vote of 4 Pin
Ujjval Shukla6-Jun-15 19:25
memberUjjval Shukla6-Jun-15 19:25 
NewsCode Pin
Member 1145043913-Feb-15 5:14
memberMember 1145043913-Feb-15 5:14 
GeneralRe: Code Pin
Abhishek Jaiswall18-Feb-15 0:44
memberAbhishek Jaiswall18-Feb-15 0:44 
Suggestion[My vote of 2] Missing some very important points Pin
Assorted Trailmix9-Sep-14 17:39
memberAssorted Trailmix9-Sep-14 17:39 
GeneralRe: [My vote of 2] Missing some very important points Pin
Abhishek Jaiswall10-Sep-14 6:46
memberAbhishek 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
memberAbhishek Jaiswall9-Sep-14 6:02 
Questionoverhiding? Pin
Paulo Zemek8-Sep-14 4:54
professionalPaulo Zemek8-Sep-14 4:54 
SuggestionRe: overhiding? Pin
Sam Hobbs9-Sep-14 6:16
memberSam Hobbs9-Sep-14 6:16 
AnswerRe: overhiding? Pin
pwasser9-Sep-14 13:59
memberpwasser9-Sep-14 13:59 
AnswerRe: overhiding? Pin
Hatredalper25-Jun-15 22:36
memberHatredalper25-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
memberAbhishek 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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171017.1 | Last Updated 8 Sep 2014
Article Copyright 2014 by Abhishek Jaiswall
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid