Introduction:

In this article we will explain to what is Method Overriding in c# or how to create a same name method in base class and child class in c# or how to use Method Overriding in c# or how to Overriding a Method in c# with example.

Description:

The process of creating same name method with same signatures in base class and derived class is called as method Overriding. Overriding also called as run time polymorphism or dynamic polymorphism. Method overriding or run time polymorphism means same method names with same signatures in base class and derived class. Method overriding is possible only in child classes or derived class, but not within the same class. 

In this method overriding or run time polymorphism we can override a method in base class by creating same method in derived class this can be achieved by using inheritance and using “virtual & override” keywords.

C# provides two options the derived class to override a method of the base class, by using virtual methods and abstract methods.

Example for Method Overriding in C# by using virtual keywords:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class BaseClass
    {
        public virtual string GetUserName()
        {
            return "Aditya Kumar Patel";
        }
    }
    class DerivedClass : BaseClass
    {
        public override string GetUserName()
        {
            return "Rajeev Kumar";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            DerivedClass obj = new DerivedClass();
            string Name = obj.GetUserName();
            Console.WriteLine(Name);
            Console.Read();
        }
    }     }

 

 

Example for Method Overriding in C# by using abstract keywords:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    abstract class BaseClass
    {
        public abstract string GetUserName();
 
    }
    class DerivedClass : BaseClass
    {
        public override string GetUserName()   //It is mandatory to implement absract method
        {
            return "Rajeev Kumar";
        }            }
    class Program
    {
        static void Main(string[] args)
        {
            DerivedClass obj = new DerivedClass();
            string Name = obj.GetUserName();
            Console.WriteLine(Name);
            Console.Read();
        }
    }
}


I hope this article will help to you.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

You may also like