In c#, the virtual keyword is useful to override base class members such as properties, methods, etc., in the derived class to modify it based on our requirements.
Following is a simple example of defining a method with the virtual keyword in the c# programming language.
If you observe the above code snippet, we defined a GetInfo method with the virtual keyword. The GetInfo method can be overridden by any derived class that inherits properties from a base class called Users.
Generally, whenever the virtual method is invoked, the run-time object will check for an overriding member in the derived class. If no derived class has overridden the member, then the virtual method will be treated as an original member.
In c#, by default all the methods are non-virtual, and we cannot override non-virtual methods. If you want to override a method, you need to define it with the virtual keyword.
The virtual keyword in c# cannot be used with static, abstract, private, or override modifiers. In c#, the virtual inherited properties can be overridden in a derived class by including a property declaration that uses the override modifier.
Following is the example of using a virtual keyword to allow class members to be overridden in a derived class in the c# programming language.
If you observe the above example, we are overriding a base class (BClass) methods and properties which we defined with a virtual keyword in a derived class (DClass) using the override keyword.
When you execute the above c# program, you will get the result below.
This is how we can use virtual keyword in c# to allow class members, such as methods, properties, etc., to be overridden in a derived class based on our requirements.