Polymorphisme in C# – Programming, Pseudocode Example, C# Programming Example

Polymorphisme in C#

The term polymorphism indicates the ability to define methods and properties of the same name, so that, for example, a derived class can redefine a base class method with the same name.

Let’s continue to use our Person and Student classes created in the previous lesson to understand the concept of polymorphism. Initially, we defined the public void PostMessage () method in the Person class, but we have not yet written its contents. We want this routine to display the person’s personal information.

It is natural to think that, in the same way, the Student class has a PostMessage () method that shows, in addition to personal information, that of a student. We must therefore define the methods as follows:

The PostMessage () method is defined in both classes, but behaves differently, since the class in the Student class also displays the registration number.

The corresponding ShowMessage () method will be called when declaring a Person or Student object. To do this, we used the polymorphism: the method DisplaysMessage () in the base class is declared using the keyword “virutal” (which corresponds to Overridable in Visual Basic.NET): with this one, we let’s say we can get another definition for the same routine in a derived class.

In fact, PostMessage () was defined by entering the keyword “override” (Overrides in VB): in this way, it is said that this function overwrites a process of the same name that was defined in the base class.

In some cases, it may be necessary in the redefined method to recall the method to be redefined. In our example, the PostMessage () method of the Student class can recall Person’s PostMessage () method, which already shows the first name and last name, and only displays the basic information of a student.

To do this, we must use the keyword “base” which, as mentioned in the previous lesson, allows us to access the derivation class; in the light of these considerations, the method DisplaysMessage () becomes:



Basically, PostMessage () calls the corresponding method in the base class.

There is another way to exploit polymorphism, using the ‘new’ keyword (equivalent to Shadows in VB.NET), which hides a basic class definition of the same name. The example above, using “new”, becomes:


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.