Home > Code Analysis > CodeRush code issues for virtual members

CodeRush code issues for virtual members

August 19th, 2011

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:

CodeRush Code Issues -Virtual member cannot be private

How to fix:

  • Change the ‘private’ visibility to ‘public’, for example:

CodeRush Virtual Member Cannot Be Private Fix

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:

CodeRush Code Issues - Virtual member cannot be declared in sealed class

How to fix:

  • Remove the ‘virtual’ modifier from the member, if appropriate:

CodeRush Virtual Member Cannot Be Declared In Sealed Class Fix 1

  • Remove the ‘sealed’ modifier from the class, if appropriate:

CodeRush Virtual Member Cannot Be Declared In Sealed Class Fix 2

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:

CodeRush Code Issues - Virtual member cannot be declared in structures

How to fix:

  • Convert the class to a structure, if appropriate:

CodeRush Virtual Member Cannot Be Declared In Structures Fix 1

  • Do not mark the member as ‘virtual’, if appropriate:

CodeRush Virtual Member Cannot Be Declared In Structures Fix 2

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

Similar Posts: