SoFunction
Updated on 2025-03-06

Analysis of the difference between polymorphism, overloading and rewriting in C#

This article summarizes the concepts and differences between polymorphism, overloading and rewriting in C#. It has good reference value for beginners. Share it for your reference. The specific analysis is as follows:

RewriteIt refers to overriding the method of the base class. The method in the base class must have a modifier virtual, and the method of the subclass must specify override.

The format is as follows:

1. In the base class:

public virtual void myMethod() 
{ 
} 

2. In subclasses:

public override void myMethod() 
{ 
} 

After rewriting, the myMethod() method is accessed with the base class object and the subclass object. As a result, both access methods redefined in the subclass. The base class method is equivalent to being overwritten.

Overload:Used to select an optimal function member to implement the call given a parameter list and a set of candidate function members.

public void test(int x,int y){} 

public void test(int x,ref int y){} 

public void test(int x,int y,string a){} 

Features of overloading:

I.The method name must be the same

II.The parameter list must be different, regardless of the order of the parameter list

III.The return value type may be different

But if there are generics, you should pay attention!

Polymorphism:The polymorphism of C# is mainly reflected in the inheritance of classes:

When a subclass inherits the parent class, there may be cases where the same name is but the method definition is different.
Therefore, the original method will be overwritten in the subclass to realize its own requirements.

There are two things to note:

①. Methods that can be rewritten in subclasses must be marked as virtual, abstract, override (rewrite) Functions marked as virtual and abstract are created for rewriting. Functions marked as override themselves are rewritten by the first two functions, so it is natural that it can be rewritten;

②. Rewritten functions must appear in subclasses, and any function of the parent class can only be rewritten once in one of its subclasses. (This is easy to understand. When you want to rewrite twice, two functions with the same return type, method name and parameter list will be defined in the subclass, which is certainly impossible).

I believe that this article has certain reference value for everyone's learning of C# programming.