In c#, Method Overriding means override a base class method in the derived class by creating a method with the same name and signatures to perform a different task. The Method Overriding in c# can be achieved using override & virtual keywords and the inheritance principle.
If we want to change the behavior of the base class method in a derived class, then we need to use method overriding. The base class method we want to override in the derived class needs to be defined with a virtual keyword. We need to use the override keyword in the derived class while defining the method with the same name and parameters then only we can override the base class method in a derived class.
In c#, the Method Overriding is also called run time polymorphism or late binding. Following is the code snippet of implementing a method overriding in c# programming language.
If you observe the above code snippet, we created two classes (“Users”, “Details”), and the derived class (Details) is inheriting the properties from the base class (Users). We are overriding the base class method GetInfo in the derived class by creating a method with the same name and parameters, and this is called a method overriding in c#.
Here, we defined a GetInfo method with a virtual keyword in the base class to allow the derived class to override that method using the override keyword.
As discussed, only the methods with a virtual keyword in the base class are allowed to override in derived class using override keyword.
Following is the example of implementing a method overriding in c# programming language.
When we execute the above c# program, we will get the result as shown below.
This is how we can achieve method overriding in c# to override a base class method in child class by defining a method with the same name and signatures based on our requirements.
The following are the difference between method overloading and method overriding in the c# programming language.
Type | Description |
---|---|
Method Overloading | Method Overloading means defining multiple methods with the same name but with different parameters. |
Method Overriding | Method Overriding means override a base class method in the derived class by creating a method with the same name and parameters using virtual and override keywords. |