EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Method Overriding in C#

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » C# Tutorial » Method Overriding in C#

Method Overriding in C#

Introduction on Method Overriding in C#

Method Overriding is a commonly used functional operation in the C# programming, where there is a requirement for overriding the operations defined in the base class by making use of the derived class. For a successful overriding, the method is expected to be a static method, member classification and access modifiers should be of same type in both base and derived methods, and the overriding can be applied only on the derived class & not on the base class. The other names given for method overriding are run time polymorphism, dynamic polymorphism and late binding.

Introduction on Method Overriding in C#

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

How to Use Overriding in C#?

Suppose, our application has the requirement to change the behavior of the base class method in a derived class, then we should go for method overriding. To achieve this, we need to create the method in the derived class with the same signature in the base class to perform a different task.  Before we learn how to use the overriding technique, we need to keep in mind the below points.

  • In C# programming, the Method Overriding is also called Run time polymorphism, Late binding or Dynamic Polymorphism.
  • Only in the derived classes method overriding is possible. Because a method is overridden in the derived class from the base class.
  • The method should be a non-virtual or static method for an override.
  • Access level modifier of both the override method and the virtual method should be the same.

The method which is overridden by the override declaration is called the overridden base method. This will be present in the base class. The overridden base method can be either abstract, override or virtual. Fresh implementation called, override method is inherited from this base class.

We use different keywords for method overriding. They are,

1. Virtual Keyword

We the compiler encounters the virtual keyword in the program, it understands that this method can be overridden by any of its derived classes. The structure is as below.

public virtual int EnemyHealth()
{
Console.WriteLine("Enemy Health");
}

2. Override Keyword

This is present in the derived class. It tells the compiler that this method is overriding the method with the same name and signature in the base class.

public override int EnemyHealth ()
{
Console.WriteLine("Enemy 1");
}

Example

First, let us look into the example without using the Virtual and override keyword.

Popular Course in this category
C# Training Program (6 Courses, 17 Projects)6 Online Courses | 17 Hands-on Project | 89+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.6 (8,847 ratings)
Course Price

View Course

Related Courses
ASP.NET Training (8 Courses, 19 Projects).NET Training Program (4 Courses, 19 Projects)

Code:

class Birds
{
public void Color( )
{
Console.WriteLine("Birds will have different Colors");
}
}
class Parrot:Birds
{
public void Color( )
{
Console.WriteLine("Parrot is Green");
}
}
class ExecutionClass
{
public static void Main( )
{
Birds object;
object = new Birds( );
object .Color( );
object = new Parrot( );
object.Color( );
}
}

Output:

Output method

In the above example, we created an object of Derived class Parrotand storing its reference in the reference variable object of the type Birds.

In the next step, using the reference variable object we invoke the function Color (). Since object contains a reference to an object of type Parrot, it is natural that we expect the function Color () of class Parrot to get executed. But we are wrong. The beauty of the programming won’t allow it to happen.

To our surprise, what is executed is the Color () method of Birds class. That’s because the function is invoked based on the type of reference and not to what the reference variable object refers to. Since object is a reference of type Birds, the function Color () of class Birds will be invoked, no matter whom object refers to.

Now let’s rewrite the same program with virtual and override This time we will go step by step for a better understanding.

Create a base class with any name. Here I am using Birds. Write a method with the virtual keyword. This will be our overridden method which we will override in the inherited class. Inside the method write some message to print in the console.

class Birds
{
public virtual void Color( )
{
Console.WriteLine("Birds will have different Colors");
}
}

Now create one more class Parrot This time we will inherit it from the base class which we created earlier i.e. Birds. To inherit we use the ‘:’ symbol.

class Parrot: Birds

Here write a function with override keyword and write some message. Make sure that the method name and signature in the derived class match with the method name and signature in the base class.

public override void Color ( )
{
Console.WriteLine("Parrot is Green");
}

We need one more class to execute the functionality to check the overriding. Create a class with any name. Inside that write the Main function.

class ExecutionClass
{
public static void Main( )
{
}
}

Create an object of the parent class and trigger the function using the object of the class. This will invoke the Color method present in the Birds class.

Birds object;
object = new Birds( );
object .Color( );

Now create the object of the derived class and call the Color method. This will invoke the Color method of the Parrot class.

object = new Parrot( );
object.Color( );

Can you guess the output when we run the program? This is as shown below.

Output:

Output run

The Keywords override and virtual allows to invoke the base class and derived class methods separately at any point of time, even if the method names and signatures are the same.

Conclusion

In this article we understood the method overriding, need of the method overriding, real-world example of the overriding principle, the way to achieve it, the necessity of using the virtual and override keywords and the example of overriding using the code. We can conclude that overriding is one of the useful features in polymorphism which we can change the behavior of the base class method in the derived class.

Recommended Articles

This is a guide to Method Overriding in C#. Here we discuss the Introduction, How to use overriding and different keywords for Method Overriding along with Examples and Steps. You may also look at the following articles to learn more –

  1. What is Multithreading in C#?
  2. Overriding in C++
  3. Overriding in Java
  4. Multithreading in C#

C# Training Program (6 Courses, 17 Projects)

6 Online Courses

17 Hands-on Project

89+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C sharp Tutorial
  • overloading and overrideing
    • Overloading and Overriding in C#
    • Overloading in C#
    • Overriding in C#
    • Method Overloading in C#
    • Method Overriding in C#
    • Operator Overloading in C#
  • Basic
    • Uses Of C#
    • C# Versions
    • C# Data Types
    • Variables in C#
    • Namespaces in C#
    • C# Compilers
    • C# Keywords
    • Iterators in C#
    • Objects in C#
    • C# Object Dispose
    • C# object to XML
    • C# check object type
    • C# Object Serialization
    • Pointers in C#
    • C# Literals
    • C# Commands
    • C# Custom Attribute
    • Type Casting in C#
    • String vs String C#
    • C# Struct vs Class
  • Operators
    • Logical Operators in C#
    • Conditional Operators in C#
    • Bitwise Operators in C#
    • C# OR Operator
    • C# Ternary Operators
    • Operator Precedence in C#
  • Control Statement
    • C# if Statement
    • Else If in C#
    • Continue in C#
    • Break in C#
    • Switch Statement in C#
    • Goto Statement in C#
  • Loops
    • C# For Loop
    • C# While Loop
    • C# do-while loop
    • C# foreach Loop
  • Arrays
    • Arrays in C#
    • 2D Arrays in C#
    • C# Jagged Arrays
    • String Array in C#
    • C# Multidimensional Arrays
  • Constructor and Destructor
    • Constructor in C#
    • Copy Constructor in C#
    • Static Constructor in C#
    • Destructor in C#
  • Functions
    • C# Functions
    • C# String Functions
    • Math Functions in C#
    • Recursive Function in C#
    • C# Anonymous Functions
    • C# Local Functions
    • Enum in C#
    • Trim() in C#
    • clone() in C#
    • C# random
    • C# String Format()
    • C# String Interpolation
    • C# StartsWith()
    • C# String IndexOf()
    • DateTime in C#
    • C# Nullable
    • C# nameof
    • C# checked
    • C# String PadLeft
    • Convert String to Double in C#
    • Convert int to String C#
    • String to Date C#
    • C# intern()
    • C# Stopwatch
    • C# DirectoryInfo
    • C# Compare()
    • C# Base
    • C# SOAP
    • Lock in C#
  • Advanced
    • Inheritance in C#
    • Exception Handling in C#
    • Types of Exception in C#
    • C# FileNotFoundException
    • C# NullReferenceException
    • C# OutOfMemoryException
    • C# StackOverflowException
    • Custom Exception in C#
    • What is Multithreading in C#
    • C# finally
    • C# System.IO
    • What is StringBuilder in C#
    • DataReader C#
    • BinaryWriter in C#
    • C# BinaryReader
    • TextWriter in C#
    • TextReader in C#
    • C# StringReader
    • C# StringWriter
    • C# StreamReader
    • C# StreamWriter
    • C# FileInfo
    • What is Design Pattern in C#?
    • Multithreading in C#
    • Sorting in C#
    • Bubble Sort in C#
    • C# SortedList
    • C# SortedSet
    • C# SortedDictionary
    • Abstract Class in C#
    • Access Modifiers in C#
    • C# Generics
    • Deserialization in C#
    • C# Thread
    • C# Thread Join
    • C# Thread Sleep
    • C# Thread Synchronization
    • C# Class
    • Sealed in C#
    • Sealed Class in C#
    • Polymorphism in C#
    • C# Call By Reference
    • Virtual Keyword in C# 
    • Yield Keyword in C#
    • Regular Expression in C#
    • C# Lambda Expression
    • C# Predicate
    • Convert Object to JSON C#
    • Checkbox in C#
    • C# MessageBox
    • Collections in C#
    • List in C#
    • C# LinkedList
    • Listbox in C#
    • Protected in C#
    • C# EventHandler
    • Private in C#
    • this Keyword in C#
    • Static Keyword in C#
    • C# Out Parameter
    • Assert in C#
    • C# Delegates
    • C# Interface
    • Generics in C#
    • Timer in C#
    • C# Serialization
    • Metadata in C#
    • C# Stack
    • C# Using Static
    • Queue in C#
    • C# File.Exists
    • C# Tuples
    • C# Create JSON Object
    • Partial in C#
    • C# readonly
    • C# Action Delegate
    • C# Await Async
    • C# Dictionary
    • IEnumerable C#
    • C# Data Grid View
    • C# Dynamic
    • Web Services in C#
    • C# Pattern Matching
    • C# Extension Methods
    • C# XmlSerializer
  • Programs
    • Patterns in C#
    • Swapping in C#
    • Palindrome in C#
    • Factorial in C#
    • Fibonacci Series in C#
    • Random Number Generator in C#
    • Prime Numbers in C#
    • Armstrong Number in C#
    • Reverse String in C#
  • Interview questions
    • C# Interview Questions and Answers
    • C# OOP Interview Questions
    • C# Design Pattern Interview Questions

Related Courses

C# Certification Training

ASP.NET Course

.NET Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C# Training Program (6 Courses, 17 Projects) Learn More