What is the usage of “override” in C#?
In C#, the override keyword is used to rewrite a base class method in a subclass. When a subclass wants to modify or extend a base class method, the override keyword can be used. Here is how you can use the override keyword:
- The subclass method must have the same name, return type, and parameters as the base class method.
- Subclass methods must be marked with the override keyword.
- The subclass method can call the base class method in the method body using the base keyword.
- The override method can be used to add, modify, or remove functionality from a base class method.
- Subclass methods cannot use stricter access modifiers than the base class methods. For example, if the base class method is protected, then subclass methods can only use protected or less restrictive modifiers.
- The subclass method cannot use the static keyword because static methods cannot be overridden.
By using the override keyword, a subclass can modify or extend methods inherited from the base class according to specific requirements, thus achieving polymorphism and extensibility.