Tuesday 10 November 2015

How to use Method Overriding in C# .Net?

How to use Method Overriding in C# .Net? Creating a method in derived class with same signature as a method in base class is called as ... thumbnail 1 summary

How to use Method Overriding in C# .Net?

Creating a method in derived class with same signature as a method in base class is called as method overriding.

Same signature means methods must have same name, same number of arguments and same type of arguments.

Method overriding is possible only in derived classes, but not within the same class.


When derived class needs a method with same signature as in base class, but wants to execute different code than provided by base class then method overriding will be used.

Example

using System;


namespace methodoverriding

{

    class BaseClass

    {

        public virtual  string YourCountry()

        {

            return "India";

        }

    }


    class DerivedClass : BaseClass

    {

        public override string YourCountry()

        {

            return "USA";

        }

    }


    class Program

    {

       

        static void Main(string[] args)

        {

            DerivedClass obj = new DerivedClass();

            string Country = YourCountry();

            Console.WriteLine(Country);

            Console.Read();

        }

    }

}


Output

USA

6 comments