What is the usage of “virtual” in C#?

In C#, the virtual keyword is used to define methods, properties, or indexers that can be overridden in derived classes. It allows derived classes to provide their own implementation using the override keyword.

Using the ‘virtual’ keyword allows for the creation of a virtual member, meaning that this member can be overridden in a derived class. This allows the derived class to change the behavior defined in the base class by providing its own implementation. This feature is one of the key aspects in achieving polymorphism in object-oriented programming.

The syntax for using the virtual keyword is as follows:

public virtual returnType MethodName(parameter)
{
    // 方法实现
}

Members defined in a base class with the ‘virtual’ keyword can be overridden by derived classes, while members defined without the ‘virtual’ keyword cannot be overridden. When overriding a virtual method in a derived class, the ‘override’ keyword must be used.

public override returnType MethodName(parameter)
{
    // 新的方法实现
}

Only methods, properties, or indexers with public, protected, or internal modifiers can be overridden.

When overriding a virtual member of a base class in a derived class, you can use the base keyword to call the implementation in the base class.

The use of the virtual keyword allows for polymorphism, which means calling the appropriate method based on the actual type of object at runtime. This enables changing the behavior in the base class through overrides in the derived class without modifying the base class code.

bannerAds