• How to override a Method in C# ASP.NET

    by  • January 21, 2016 • Microsoft .NET C# (C-Sharp) • 0 Comments

    Here we will discuss to override a method in our C# Program. Method Override is an object oriented language feature that allows a subclass to provide a specific implementation of a method that is already provided by super class. The overridden methods must have the same signature as that of base class methods.

    First we will learn a little about inheritance. We inherit a class by colon (:) sign followed by the parent class name. Suppose we have parent class Car that defines a method ShowDetails. We derived a class Mercedes from parent class Car. Now the method ShowDetails is also accessible in derived class. In the main method we create instance of derived class and access the ShowDetails method of parent class as shown below output;

    The Output below show we have access the parent class method through base class.

    inheritance output

    Now we will override the parent class methods. Method Override is an object oriented language feature that allows a subclass to provide a specific implementation of a method that is already provided by super class.

    Lets look at the code.

    In the above code we define a base class car. This class defines a method ShowDetails. Then we derived two classes Mercedes and MiniVan from base class Car. Each derived class also defines a show details methods.  In the main method, we created instance of the derived classes and call its methods ShowDetails().

    Virtual keyword is used to generating virtual path for its derived classes on implementing method overridden. Override keyword is used in the derived class to override base class method.

    We we run the program, we will see the following given output;

    Override Output

     




    Namecheap.com

    Leave a Reply