Base and Virtual Keyword in C#


The Base keyword is used to refer to the base class when chaining constructors or when you want to access a member (method, property, anything) of base class that has been overridden or hidden in the current class i.e in Derived Class. For example,

Virtual Keyword: This keyword can be used to the method, if we have to override that method in the derived class.

using System;
namespace BaseKeyword_Example
{
    class Program
    {
        static void Main(string[] args)
        {
            Class2 obj = new Class2();
            obj.MyTest();//Output: I am from base class virtual method
            obj.Test();   //Output: I am from class 2 ovveride Method
            Console.ReadLine();
        }
    }
   public class Class1
    {
       public virtual void Test()
       {
           Console.WriteLine("I am from base class virtual method");
       }
    }
   class Class2:Class1
   {
       public override void Test()
       {
           Console.WriteLine("I am from class 2 override Method");
       }
       public  void MyTest()
       {
           base.Test(); // here we are calling base class method.                          
       }
   }
}

Summary:

We saw that base keyword is used to call the base class method in derived class. Only if that method had been overridden in class.

Virtual keyword can be used if we have to override that method in derived class.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.