SoFunction
Updated on 2025-03-08

C# uses virtual methods to implement polymorphism

This article describes the use of virtual methods to implement polymorphism in C#. Share it for your reference. The specific analysis is as follows:

Let’s look at an example. If there is an animal class, the method cry() is used to describe the animal’s call, and the call of different animals is different. According to the inherited characteristics, if the content of the public part of the class is placed in the parent class, the cry() method should be placed in the parent class. The program is written according to this idea as follows:

using System;
class Anmial
{
public void Cry()
{
("This is the animal's call");
}
}
class Dog: Anmial
{
public void Run()
{
  ("Dog Ruth fast");
}
}
class Cat: Anmial
{
public void Look()
{
  ("The cat looks good");
}
}
class Test
{
static void Main()
{
  Dog mydog = new Dog();
  ();
  ();
  Cat mycat = new Cat();
  ();
  ();
  ();
}
}

After running, I found that the dog and cat meowed the same, and both called the parent class Cry() method. Now I hope that the call of different animals can be reflected in the same method Cry(), so in the subclass, Cry() should be redescribed, that is, rewrite the Cry() method.

The rewrite method is to modify its implementation, or rewrite it in a derived class. Methods declared with virtual keyword in the parent class can be overridden in the subclass, which is a virtual method. The syntax of a virtual method is as follows:

Access modifier virtual return type method name()
{
//Method body
}

The virtual method declared in the parent class, if you rewrite it in the subclass, you can use the override keyword, which means you can change the virtual keyword to override, and then modify the code in the method body.

Let's modify the above code:

using System;
class Anmial
{
  public virtual void Cry()
{
("This is the animal's call");
}
}
class Dog: Anmial
{
public override void Cry()
{
("This is the barking of a dog");
}
}
class Cat: Anmial
{
public override void Cry()
{
("This is the cat's meow");
}
}
class Test
{
static void Main()
{
  Dog mydog = new Dog();
  ();
  Cat mycat = new Cat();
  ();
  ();
}
}

Note: The access level of the parent class method is the same as the access level of the subclass override method, i.e. they should have the same access modifier.
For example:

public virtual void Hello()

Cannot be rewritten as:

private override void Hello()

I hope this article will be helpful to everyone's C# programming.