C# | Method Overriding - GeeksforGeeks (2024)

Table of Contents
C# C# C# C# C# Please Login to comment...

Last Updated : 15 Mar, 2023

Comments

Improve

Method Overriding in C# is similar to the virtual function in C++. Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class. Creating a method in the derived class with the same signature as a method in the base class is called as method overriding.

In simple words, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signature and same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override the method in the super-class. Method overriding is one of the ways by which C# achieve Run Time Polymorphism(Dynamic Polymorphism).

The method that is overridden by an override declaration is called the overridden base method. An override method is a new implementation of a member that is inherited from a base class. The overridden base method must be virtual, abstract, or override.

C# | Method Overriding - GeeksforGeeks (1)

Example:

class base_class{ public void gfg();}class derived_class : base_class{ public void gfg();}class Main_Method{ static void Main() { derived_class d = new derived_class(); d.gfg(); }}

Here the base class is inherited in the derived class and the method gfg() which has the same signature in both the classes, is overridden.

In C# we can use 3 types of keywords for Method Overriding:

  • virtual keyword: This modifier or keyword use within base class method. It is used to modify a method in base class for overridden that particular method in the derived class.
  • override: This modifier or keyword use with derived class method. It is used to modify a virtual or abstract method into derived class which presents in base class.
class base_class{ public virtual void gfg();}class derived_class : base_class{ public override void gfg();}class Main_Method{ static void Main() { derived_class d = new derived_class(); d.gfg(); base_class b = new derived_class(); b.gfg(); }}

Here first, d refers to the object of the class derived_class and it invokes gfg() of the class derived_class then, b refers to the reference of the class base and it hold the object of class derived and it invokes gfg() of the class derived. Here gfg() method takes permission from base class to overriding the method in derived class.

Example 1: Method Overriding without using virtual and override modifiers

C#

// C# program to demonstrate the method overriding

// without using 'virtual' and 'override' modifiers

using System;

// base class name 'baseClass'

class baseClass

{

public void show()

{

Console.WriteLine("Base class");

}

}

// derived class name 'derived'

// 'baseClass' inherit here

class derived : baseClass

{

// overriding

new public void show()

{

Console.WriteLine("Derived class");

}

}

class GFG {

// Main Method

public static void Main()

{

// 'obj' is the object of

// class 'baseClass'

baseClass obj = new baseClass();

// invokes the method 'show()'

// of class 'baseClass'

obj.show();

obj = new derived();

// it will invokes the method

// 'show()' of class 'baseClass'

obj.show();

}

}

Output:

Base classBase class

Explanation: In this program, the object obj invokes class baseClass two times and call the method show() of class baseClass. To avoid this problem we use virtual and override keyword.

Example 2: Method overriding using virtual and override modifiers.

C#

// C# program to illustrate the use of

//'virtual' and 'override' modifiers

using System;

class baseClass {

// show() is 'virtual' here

public virtual void show()

{

Console.WriteLine("Base class");

}

}

// class 'baseClass' inherit

// class 'derived'

class derived : baseClass

{

//'show()' is 'override' here

public override void show()

{

Console.WriteLine("Derived class");

}

}

class GFG {

// Main Method

public static void Main()

{

baseClass obj;

// 'obj' is the object

// of class 'baseClass'

obj = new baseClass();

// it invokes 'show()'

// of class 'baseClass'

obj.show();

// the same object 'obj' is now

// the object of class 'derived'

obj = new derived();

// it invokes 'show()' of class 'derived'

// 'show()' of class 'derived' is overridden

// for 'override' modifier

obj.show();

}

}

Output:

Base classDerived class
  • base Keyword: This is used to access members of the base class from derived class. It basically used to access constructors and methods or functions of the base class. The base keyword cannot use within a static method. Base keyword specifies which constructor of the base class should be invoked while creating the instances of the derived class.

Use of Base keyword:

  • Call methods or functions of base class from derived class.
  • Call constructor internally of base class at the time of inheritance.

Example 3:

C#

// C# program to show the use of 'base'

// keyword in method overriding

using System;

// base class

public class web {

string name = "GeeksForGeeks";

// 'showdata()' is member method,

// declare as virtual

public virtual void showdata()

{

Console.WriteLine("Website Name: " + name);

}

}

// derived class

// class 'web' is inherits

// class 'stream'

class stream : web {

string s = "Computer Science";

//'showdata()' is overridden

// in derived class

public override void showdata()

{

// Calling 'showdata()' of base

// class using 'base' keyword

base.showdata();

Console.WriteLine("About: " + s);

}

}

class GFG {

// Main Method

static void Main()

{

// 'E' is object of class stream

// also works as object of

// class 'web'

stream E = new stream();

// it first invokes 'showdata()'

// of class 'web' then it invokes

// 'showdata()' of class 'stream'

E.showdata();

}

}

Output:

Website Name: GeeksForGeeksAbout: Computer Science

Example 4: How the base keyword specifies the calling of base-class constructor from derived class when derived class instances are created.

C#

// C# program to show how base keyword

// specifies the calling of base-class

// constructor from the derived class

// when derived class instances are created

using System;

// base class

public class clssA {

int n1, n2;

// default constructor

public clssA()

{

Console.WriteLine("Default Constructor Invoked");

}

// parameterized constructor

public clssA(int i, int j)

{

// construct values

n1 = i;

n2 = j;

Console.WriteLine("Parameterized Constructor Invoked");

Console.WriteLine("Invoked Values are: " + n1 + " and " + n2);

}

}

// derived class

public class DerivedClass : clssA

{

// This constructor will instantiate

// 'clssA()' [no argument constructor]

// using 'base' keyword

public DerivedClass() : base() { }

// This constructor will instantiate

// 'clssA(int i, int j)' [parameterized

// constructor] using 'base' keyword

public DerivedClass(int i, int j) : base(i, j) { }

// Main Method

static void Main()

{

// invoke no argument constructor

DerivedClass d1 = new DerivedClass();

Console.WriteLine();

// invoke parameterized constructor

DerivedClass d2 = new DerivedClass(10, 20);

}

}

Output:

Default Constructor InvokedParameterized Constructor InvokedInvoked Values are: 10 and 20

Example 5: It shows how base keyword specifies the base-class constructor called from derived class and also calling of a method using the base keyword from the derived class.

C#

// C# program to show how 'base' keyword specifies

// the base-class constructor that called from

// derived class and also calling a method 'swap'

// from derived class using base keyword

using System;

// base class

public class clssA {

public int n1, n2;

// default constructor

public clssA()

{

Console.WriteLine("In clssA 'no argument constructor' invoked");

}

// parameterized constructor

public clssA(int i, int j)

{

// construct values

n1 = i;

n2 = j;

Console.WriteLine("in clssA 'parameterized constructor' invoked");

Console.WriteLine("the invoked values are " + n1 + " and " + n2);

Console.WriteLine();

}

public virtual void swap()

{

Console.WriteLine("swap function of base class(clssA) invoked");

Console.WriteLine("Before swap num1 = {0} and num2 = {1}", n1, n2);

// swapping

int t = n1;

n1 = n2;

n2 = t;

Console.WriteLine("After swap num1 = {0} and num2 = {1}", n1, n2);

}

}

// derived class

public class DerivedClass : clssA {

// This constructor will instantiate

// 'clssA' [no argument constructor]

// using 'base' keyword

public DerivedClass() : base() { }

// This constructor will instantiate

// 'clssA' [parameterized constructor]

// using 'base' keyword

public DerivedClass(int i, int j) : base(i, j) { }

public override void swap()

{

// it access the swap function of

// 'clssA' using 'base' keyword

base.swap();

Console.WriteLine();

Console.WriteLine("Swap function of derived class invoked");

Console.WriteLine("Before swap num1 = {0} and num2 = {1}", n1, n2);

// swapping

int t = n1;

n1 = n2;

n2 = t;

Console.WriteLine("After swap num1 = {0} and num2 = {1}", n1, n2);

}

// Main Method

static void Main()

{

// invoke no argument constructor

DerivedClass d1 = new DerivedClass();

Console.WriteLine();

// invoke parameterized constructor

DerivedClass d2 = new DerivedClass(10, 20);

// calling swap function

d2.swap();

}

}

Output:

In clssA 'no argument constructor' invokedin clssA 'parameterized constructor' invokedthe invoked values are 10 and 20swap function of base class(clssA) invokedBefore swap num1 = 10 and num2 = 20After swap num1 = 20 and num2 = 10Swap function of derived class invokedBefore swap num1 = 20 and num2 = 10After swap num1 = 10 and num2 = 20

Note:

  • Method overriding is possible only in derived classes. Because a method is overridden in the derived class from the base class.
  • A non-virtual or a static method can’t be overridden.
  • Both the override method and the virtual method must have the same access level modifier.


S

SoumikMondal

C# | Method Overriding - GeeksforGeeks (2)

Improve

Previous Article

C# | Method Parameters

Next Article

Anonymous Method in C#

Please Login to comment...

C# | Method Overriding - GeeksforGeeks (2024)
Top Articles
Bible Gateway passage: 2 Samuel 7 - English Standard Version
2 Samuel 7 - NIV - After the king was settled in his palace and the L...
Worcester Weather Underground
Washu Parking
Gomoviesmalayalam
Cad Calls Meriden Ct
Nc Maxpreps
What happens if I deposit a bounced check?
Co Parts Mn
Craigslist Cars And Trucks Buffalo Ny
Amateur Lesbian Spanking
LeBron James comes out on fire, scores first 16 points for Cavaliers in Game 2 vs. Pacers
Skylar Vox Bra Size
MindWare : Customer Reviews : Hocus Pocus Magic Show Kit
ExploreLearning on LinkedIn: This month's featured product is our ExploreLearning Gizmos Pen Pack, the…
Beau John Maloney Houston Tx
Bad Moms 123Movies
Cvb Location Code Lookup
Google Feud Unblocked 6969
Directions To 401 East Chestnut Street Louisville Kentucky
Letter F Logos - 178+ Best Letter F Logo Ideas. Free Letter F Logo Maker. | 99designs
"Une héroïne" : les funérailles de Rebecca Cheptegei, athlète olympique immolée par son compagnon | TF1 INFO
Grandview Outlet Westwood Ky
360 Tabc Answers
Td Small Business Banking Login
Decosmo Industrial Auctions
Is A Daytona Faster Than A Scat Pack
Espn Horse Racing Results
Craigslist Personals Jonesboro
Spiritual Meaning Of Snake Tattoo: Healing And Rebirth!
The Banshees Of Inisherin Showtimes Near Broadway Metro
Bleacher Report Philadelphia Flyers
Star Wars Armada Wikia
NV Energy issues outage watch for South Carson City, Genoa and Glenbrook
Movies - EPIC Theatres
Grays Anatomy Wiki
Acuity Eye Group - La Quinta Photos
Craigslist Dallastx
Phone number detective
Lake Dunson Robertson Funeral Home Lagrange Georgia Obituary
Game8 Silver Wolf
Cherry Spa Madison
Walgreens Agrees to Pay $106.8M to Resolve Allegations It Billed the Government for Prescriptions Never Dispensed
“Los nuevos desafíos socioculturales” Identidad, Educación, Mujeres Científicas, Política y Sustentabilidad
Ferguson Showroom West Chester Pa
Below Five Store Near Me
Three V Plymouth
How the Color Pink Influences Mood and Emotions: A Psychological Perspective
Take Me To The Closest Ups
Craigslist Cars And Trucks For Sale By Owner Indianapolis
Selly Medaline
Lux Nails & Spa
Latest Posts
Article information

Author: Allyn Kozey

Last Updated:

Views: 6092

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Allyn Kozey

Birthday: 1993-12-21

Address: Suite 454 40343 Larson Union, Port Melia, TX 16164

Phone: +2456904400762

Job: Investor Administrator

Hobby: Sketching, Puzzles, Pet, Mountaineering, Skydiving, Dowsing, Sports

Introduction: My name is Allyn Kozey, I am a outstanding, colorful, adventurous, encouraging, zealous, tender, helpful person who loves writing and wants to share my knowledge and understanding with you.