Click here to Skip to main content
15,885,435 members
Articles / Programming Languages / C#

Virtual, Override, new and Abstract keywords

Rate me:
Please Sign up or sign in to vote.
4.79/5 (11 votes)
22 Sep 2015CPOL6 min read 23.7K   16   10
The article helps us to understand Virtual, override, abstract and new keywords in C#

Virtual, override, abstract and new keywords introduction

Virtual, override, abstract and new keywords are some of the most confused and most frequently used keywords of the object oriented concepts in C#. In this article I will explain all of these keywords and the contexts in which they are used in the C# programming with the help of adequate examples and code snippet explanations for the same.

Virtual function in C#

I want to divide this article into multiple scenarios which would help us to better understand these concepts in the C# programming language,

Case 1: Normal programming scenario

Case 2: Inheritance scenario

Case 3: Inheritance scenario with the virtual and override keywords

Case 4: Inheritance scenario with the method hiding using new keyword

Case 5: I don’t need my base class’s function to have to have any implementation(abstract)

Now let’s discuss these scenarios one by one to understand the virtual, override , new and abstract keywords in C#

Case 1: Normal programming scenario

Here I have created a class named BasicTV as shown below

public class BasicTV
{
    public void SwitchOnAndDisplay()
    {
        Console.WriteLine("Basic TV is Switched On And Display Starts");
    }
}

And this class’s instance I am creating in the Client and calling the SwitchOnAndDisplay() method as shown below,

static void Main(string[] args)
{
    BasicTV tvInst = new BasicTV();
    SwitchOnTV(tvInst);

    Console.Read();
}

public static void SwitchOnTV(BasicTV tvInst)
{
    tvInst.SwitchOnAndDisplay();
}

 

Till now everything is fine and Client can use the TV to switch on and get the display and get the result as shown in the figure below.

Class instantiating in C#

Case 2: Inheritance scenario

Now Suppose some other company comes up with another TV which is taking some of the functionalities from BasicTV(i.e. inherits from the BasicTV) but adds its own functionalities as well, as shown below(though this is not the correct way to have a class to have its own method definition as discussed in Case 4 down the line)

 

 public class AdvancedTV:BasicTV
{
    public void SwitchOnAndDisplay()
    {
        base.SwitchOnAndDisplay();
        Console.WriteLine("Switch On Colorfull display");
    }

    public void ChangeColors()
    {
        Console.WriteLine("You can change the colors too!!");
    }
}

 

And I change the Client application to use the advanced TV’s instance as shown below, without changing the SwitchOnTV() method’s definition.

 

BasicTV tvInst = new AdvancedTV();
SwitchOnTV(tvInst);

Console.Read();

Now as we run the above client code we will get the output as shown below,

Inheritance in C#

And as we can see that it is not different from what we got in first case, why is it so? Why we didn’t get the functionalities of the AdvancedTV class even though we have created an instance of it. Let’s proceed and see the next case to overcome this functionality.

Case 3: Inheritance scenario with the virtual and override keywords

If we want to get the desired functionalities of the AdvancedTV we need to make the SwitchOnAndDisplay() as virtual in the base class(BasicTV) and override in the derived class (AdvancedTV) as shown in the following code snippet.

 

public class BasicTV
{
    public virtual void SwitchOnAndDisplay()
    {
        Console.WriteLine("Basic TV is Switched On And Display Starts");
    }
}

public class AdvancedTV:BasicTV
{
    public override void SwitchOnAndDisplay()
    {
        base.SwitchOnAndDisplay();
        Console.WriteLine("Switch On Colorfull display");
    }

    public void ChangeColors()
    {
        Console.WriteLine("You can change the colors too!!");
    }
}

And when we execute the client code we will get the output as shown in the figure below.

virtual and override in C#

How did virtual and override work?

Virtual keyword allows having an overridden version of the same method in the derived class.

In other words, Virtual and override keywords help us to provide the versioning to the methods. While runtime if the compiler sees that the particular method is defined as virtual in MethodDefinition table, it looks for the most derived and overridden method in the inheritance hierarchy as we can see from the above example. If the method is found in that case, it is called otherwise the virtual method itself is called which can be confirmed from the below code.

Here I have made the base class methods as virtual but didn’t override it in the derived class, as shown below

 

public class BasicTV
{
    public virtual void SwitchOnAndDisplay()
    {
        Console.WriteLine("Basic TV is Switched On And Display Starts");
    }
}

 

And the derived class is as same as case 2’s code in that case the output would also be the same as case 2’s output and the reason for same I have explained just above.

In Case if you want to know more about the how the virtual functions are called by compiler you can read this article.

Case 4: Inheritance scenario with the method hiding using new keyword

Now again taking the scenario of Case 2, as we have not yet provided the override keyword for the method in the derived class we will get a compile time warning as shown below

new keyword in C#

Which says that we need to decorate the SwitchOnAndDisplay() method in the derived class with the new or the override keyword.

Why do we need the new keyword?

We need the new keyword to hide the implementation of the base class’s method. As soon we have the new keyword with the derived class method definition we will no longer get this error. After adding the new keyword the class will look like as shown in the below code snippet.

 

public class AdvancedTV:BasicTV
{
    public new void SwitchOnAndDisplay()
    {
        base.SwitchOnAndDisplay();
        Console.WriteLine("Switch On Colorfull display");
        ChangeColors();
    }

    public void ChangeColors()
    {
        Console.WriteLine("You can change the colors too!!");
    }
}

 

But to call this implementation of the SwitchOnAndDisplay() we need to create a variable of type AdvancedTV itself, which helps us to understand that the derived class has its own version of the SwitchOnAndDisplay() methods and not the BasicTV as shown in the code below,

 

static void Main(string[] args)
 {
     AdvancedTV tvInst = new AdvancedTV();
     SwitchOnTV(tvInst);

     Console.Read();
 }

 public static void SwitchOnTV(AdvancedTV tvInst)
 {
     tvInst.SwitchOnAndDisplay();
 }

 

And using the above code we will be able to call the SwitchOnAndDisplay() version of the AdvancedTV class which has new keyword.
As we can see that new keyword is used to hide the implementation of the base class’s function and it tells the compiler that the method which uses new keyword does not have any relationship with the same method which is present in the base class.

Case 5: I don’t need my base class’s function to have to have any implementation

Till now we have seen that our base class has a method which provides its own definition to achieve the functionality. Now the developer of the BasicTV sees that the SwitchOnAndDisplay() method’s functionality is very common any class deriving from Basic TV need’s to have this functionality. This programming concept he can achieve by declaring the BasicTV class and the method as abstract as shown below:

 

public abstract class BasicTV
{
    public abstract void SwitchOnAndDisplay();

    public void SwitchOnTheTV()
    {
        Console.WriteLine("TV is Switched On");
    }
}

 

Abstract class is the class which cannot be instantiated and which can contains one or more abstract methods.

Abstract methods are the methods which are present only with the signature in the defining classes, they don’t have any implementation in the defining class.
Abstract classes are defined to have a sole purpose of being inherited.
Interfaces in C# can also serve the purpose of only having the abstract methods but they cannot have any method with implementation. As is the case with abstract classes which you can see in my above example in which I have one method which also has its own implementation in the class.

Now I can have any number of classes which can inherit from the abstract class. In my case I want to have two custom classes which will inherit from the base abstract class as shown in the code snippet below .

 

public class AdvancedTV:BasicTV
{
    public override void SwitchOnAndDisplay()
    {
        base.SwitchOnTheTV();
        Console.WriteLine("Switch On Colorfull display");
        ChangeColors();
    }

    public void ChangeColors()
    {
        Console.WriteLine("You can change the colors too!!");
    }
}

public class LEDTV : BasicTV
{
    public override void SwitchOnAndDisplay()
    {
        base.SwitchOnTheTV();
        Console.WriteLine("Switch On Colorfull display with 16k Colors");
        ChangeColors();
    }

    public void ChangeColors()
    {
        Console.WriteLine("You can choose among the 16K colors!!");
    }
}

 

As seen in the above code example I have two custom classes which have their own implementation of the SwitchOnAndDisplay() method. Now at the client side I can use both of these classes as shown below

 

static void Main(string[] args)
{
    BasicTV TvInst = new AdvancedTV();
    SwitchOnTV(TvInst);


    BasicTV advTvInst = new LEDTV();
    SwitchOnTV(advTvInst);

    Console.Read();
}

public static void SwitchOnTV(BasicTV tvInst)
{
    tvInst.SwitchOnAndDisplay();
}

 

As we can see from the above code example that the SwitchOnTV() function accepts the parameter of type BasicTV which in turn can be used to pass parameters of any type derived from BasicTV as seen in the above code.

The output of the above code is:

Abstract function in C#

This was all about the abstract methods.

Conclusion:

In this article I have discussed about all the keywords (i.e. virtual, override, abstract and new) which we use for the object oriented programming point of view. Please let me know your thoughts about the article

 

The post Virtual, Override, new and Abstract keywords appeared first on Dot Net For All.

License

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


Written By
Software Developer (Senior)
India India
I have 8 years of experience of mostly developing the .NET windows as well as web applications. Passionate about learning and sharing.

Visit my personal blog to know more about the .NET technology and increase your knowledge about C# and .NET. You can always follow me on twitter @dotnetforall.

Comments and Discussions

 
GeneralOOP Pin
Member 105265991-Oct-15 5:48
professionalMember 105265991-Oct-15 5:48 
Questionwhen did you call the method :changeColors() ??? Pin
Mekki Ahmedi23-Sep-15 3:47
Mekki Ahmedi23-Sep-15 3:47 
when did you call the method :changeColors() ???
To be a good programmer, you must be a good thieve!

AnswerRe: when did you call the method :changeColors() ??? Pin
DotNetForAll28-Sep-15 16:53
DotNetForAll28-Sep-15 16:53 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun23-Sep-15 1:36
Humayun Kabir Mamun23-Sep-15 1:36 
GeneralRe: My vote of 5 Pin
DotNetForAll23-Sep-15 3:03
DotNetForAll23-Sep-15 3:03 
QuestionGood samples! Pin
irneb22-Sep-15 23:45
irneb22-Sep-15 23:45 
AnswerRe: Good samples! Pin
DotNetForAll23-Sep-15 3:02
DotNetForAll23-Sep-15 3:02 
GeneralMy vote of 5 Pin
Dineshshp22-Sep-15 23:19
professionalDineshshp22-Sep-15 23:19 
GeneralRe: My vote of 5 Pin
DotNetForAll23-Sep-15 3:01
DotNetForAll23-Sep-15 3:01 

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.