Explain Method Overriding with examples in c#?

Method Overriding: Overriding means changing the functionality of a method without changing the signature. We can override a function in base class by creating a similar function in derived class. This is done by using virtual/overrides keywords.
Base class method has to be marked with virtual keyword and we can override it in derived class using override keyword. Derived class method will completely overrides base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called.

Example:

  // Base class
    public class BaseClass
    {
        public virtual void Method1()
        {
            Console.Write("Base Class Method");
        }
    }
    // Derived class
    public class DerivedClass : BaseClass
    {
        public override void Method1()
        {
            Console.Write("Derived Class Method");
        }
    }
    // Using base and derived class
    public class Sample
    {
        public void TestMethod()
        {
            // calling the overriden method
            DerivedClass objDC = new DerivedClass();
            objDC.Method1();
            // calling the baesd class method
            BaseClass objBC = (BaseClass)objDC;
            objDC.Method1();
        }
    }

Output:

Derived Class Method
Derived Class Method

Need Help? Contact Us.

Log in

*
*

Forgot password?

*

New User

*
*
*
*