Home  >  Article  >  Backend Development  >  What is polymorphism in C#?

What is polymorphism in C#?

云罗郡主
云罗郡主Original
2019-01-15 15:39:227818browse

Polymorphism is a concept where a method can be defined more than once. But each time, the function will pass a different set of parameters. Let's use a case to explain what polymorphism is in C#. [Recommended reading: What is inheritance in C#?

What is polymorphism in C#?

Step 1) The first step is to change the code of Tutorial class, in this step we add the following code to Tutorial .cs file.

Code description:

1. In the first step, we keep the definition of the SetTutorial method.

2. We set TutorialID and TutorialName according to the parameters pID and pName.

3. This is where we make changes to our class, where we add a SetTutorial with the same name, only this time we pass only one parameter, which is pName. In this method, we just set the field of TutorialName to pName.

Step 2) The final step is to modify our main Program.cs file. In our console application, we will create an object of Guru99Tutorial class.

{
 class Tutorial
 {
  public int TutorialID; 
  public string TutorialName;
  
  public void SetTutorial(int pID,string pName) 
  {
   TutorialID=pID;
   TutorialName=pName;
  }
  public void SetTutorial(string pName) 
  {
   TutorialName=pName;
  }
  public String GetTutorial()
  {
   return TutorialName;
  }
  
  static void Main(string[] args) 
  {
   Tutorial pTutor=new Tutorial();
   
   pTutor.SetTutorial(1,"First Tutorial");
   Console.WriteLine(pTutor.GetTutorial());
   
   pTutor.SetTutorial("Second Tutorial");
   Console.WriteLine(pTutor.GetTutorial());
    
   Console.ReadKey(); 
  }
 }
}

Code analysis:

In the first step, we use SetTutorial with 2 parameters, where we pass TutorialID and TutorialName to this method.

In the second step, we now call the SetTutorial method with only one parameter, we just pass the TutorialName to this.

If you enter the above code correctly and run the program, the following output will be displayed.

Create a separate method called public int GetTutorialID and in that method write the line of code "return TutorialID", this can be used to return the TutorialID to the calling program.

Output:

What is polymorphism in C#?

From the output, we can clearly see that both methods are successfully called. Therefore, the strings "First Tutorial" and "Second Tutorial" are sent to the console.


The above is the detailed content of What is polymorphism in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn