SoFunction
Updated on 2025-03-07

The difference between abstract methods and virtual methods in C#

People who have studied C# should know about abstract methods and virtual methods, while many beginners do not know much about the difference between the two. Today, this article analyzes the differences between the two. Examples are attached to illustrate. The specific analysis is as follows:

1. Main differences:

For abstract methods, subclasses must implement it

For virtual methods, subclasses can or may not be rewritten

therefore,The two have different constraints

2. The example code is as follows:

/* Declare an abstract class
 * 1. Abstract classes can contain variables
 * 2. The method body cannot be declared in abstract methods
 */
abstract class AbsClass
{  
  string name;
  public abstract void DisplayValue(string value);
}

/* Subclasses that inherit abstract class must implement abstract methods*/
class AbsClassInherited : AbsClass
{
  /*Use override to rewrite implementation*/
  public override void DisplayValue(string value)
  {
    (());
  }
}
 /* Declare virtual functions
  */
class VirtClass
{
  /*Declare a virtual function
    The virtual function must implement the method body*/
  public virtual void DisplayValue(string value)
  {
    (value);
  }
}
/*The virtual method can be implemented or not*/
class VirtClassInherited : VirtClass
{
  /*Use override to rewrite implementation*/
  public override void DisplayValue(string value)
  {
    (());
  }
}

/* Declare an interface
  * 1. Methods in the interface must be public
  * 2. No variables are allowed in the interface
  * 3. Methods in the interface do not allow method bodies
  */
interface IAbs
{
  void DisplayValue(string value);
}

I hope the analysis done in this article will be helpful to everyone's C# programming.