CodeRush code issues for virtual members
As you probably know, if a member is declared with the ‘virtual‘ keyword, derived classes can override the implementation of this member. In a virtual member invocation, the run-time type of the instance for which that invocation takes place determines the actual member implementation to invoke: whether it is a base virtual member or an overridden member from a derived class. The virtual member is declared like an instance member with addition of a ‘virtual‘ keyword to its declaration.
The peculiarity of virtual methods defines several other rules for their declaration. If you break these rules, you will see the error when you compile your source code. To help you declare the virtual methods correctly, CodeRush suggests several code issues that allow you to write the code for virtual member declaration without making mistakes. Here they are:
Virtual member cannot be private
Cause:
Virtual members must have a visibility greater than ‘private’ because they may be overridden in derived classes. If a member has a ‘private‘ modifier, it is not visible to descendants. You will see the error when a member is marked as ‘virtual‘ and has a ‘private‘ visibility keyword at the same time.
Sample:
How to fix:
- Change the ‘private’ visibility to ‘public’, for example:
Virtual member cannot be declared in sealed class
Cause:
When the class is sealed, it cannot contain virtual members, because sealed classes cannot be inherited by other classes. Methods marked as ‘virtual‘ inside the sealed classes will show as an error.
Sample:
How to fix:
- Remove the ‘virtual’ modifier from the member, if appropriate:
- Remove the ‘sealed’ modifier from the class, if appropriate:
Virtual member cannot be declared in structures
Cause:
Virtual members are only allowed in types that can be descended from. Because you cannot inherit from a structure, you cannot declare a virtual member inside of it.
Sample:
How to fix:
- Convert the class to a structure, if appropriate:
- Do not mark the member as ‘virtual’, if appropriate:
In addition to the code issues for members marked as ‘virtual‘, there are similar code issues for members marked as ‘abstract‘ and ‘override‘.
—– Products: CodeRush Pro Versions: 12.1 and up VS IDEs: any Updated: Nov/19/2012 ID: C122