Home > Code Analysis > Code Issues specific to operators

Code Issues specific to operators

September 9th, 2011

An operator is a member that defines the meaning of applying a particular expression operator to instances of a class or structure. Three kinds of operators can be defined: unary operators, binary operators, and conversion operators. All operators have must be declared according to the language specification.

For example, C# allows you to overload operators by defining static member functions using the operator keyword. Not all operators can be overloaded, and others have restrictions. For example, the signature of an operator should consist of the name of the operator and the type of each of its formal parameters, considered in left to right order. The signature of an operator specifically does not include the result type.

CodeRush includes several code issues that make it possible to declare operators without violating the operator declaration rules at the coding stage.

Here they are:

Operator cannot be abstract

Cause:

Operators must always be implemented. It is now allowed to mark operators with an ‘abstract‘ keyword. If an operator is marked as an ‘abstract‘, the error is shown.

Sample:

CodeRush Operator cannot be abstract

How to fix:

  • Remove the ‘abstract’ modifier:

CodeRush Operator Cannot Be Abstract Fix

Operator cannot have the ‘params’ parameter

Cause:

Operators must have an unchanging number of parameters. You cannot have an undefined number of parameters for an operator by using the ‘params‘ keyword.

Sample:

CodeRush Operator cannot have params parameter

How to fix:

  • Remove the ‘params’ parameter:

CodeRush Operator Cannot Have The Params Parameters Fix

Operator must be declared static and public

Cause:

According to the language specification, operators are declared as a static member with a ‘public‘ visibility modifier.

Sample:

CodeRush Operator must be declared public and static

How to fix:

  • Mark the operator member as static and public:

CodeRush Operator Must Be Declared Static And Public Fix

Operator must declare a body

Cause:

Operators not marked with the external modifier must declare a member body. Operators without a code body will be highlighted as an error.

Sample:

CodeRush Operator must declare a body

How to fix:

  • Declare the body of the operator:

CodeRush Operator Must Declared A Body Fix

Overloaded unary operator takes one parameter

Cause:

Implicit and explicit unary operators must accept a single parameter. If unary operator takes more than one parameter, an error is shown.

Sample:

CodeRush Overloaded unary operator takes one parameter

How to fix:

  • Remove the redundant parameter, e.g.,:

CodeRush Overloaded Unary Operator Takes One Parameter Fix

—–
Products: CodeRush Pro
Versions: 12.1 and up
VS IDEs: any
Updated: Nov/19/2012
ID: C127

Similar Posts: