TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
C# Coding Standard

Rule:  7@501Checked automatically with code checker

Synopsis:Do not overload any 'modifying' operators on a class type
Severity Level:6
Category:Object oriented


In this context the 'modifying' operators are those that have a corresponding assignment operator, i.e. the non-unary versions of +, -, *, /, %, &, |, ^, << and >>.

There is very little literature regarding operator overloading in C#. Therefore it is wise to approach this feature with some caution.

Overloading operators on a struct type is good practice, since it is a value type. The class is a reference type and users will probably expect reference semantics, which are not provided by most operators.

Consider a class Foo with an overloaded operator+(int), and thus an impicitly overloaded operator+=(int). If we define the function AddTwenty as follows:

public static void AddTwenty (Foo f)
	f += 20;

Then this function has no net effect:

	Foo bar = new Foo(5);
	AddTwenty (bar);
	// note that 'bar' is unchanged
	// the Foo object with value 25 is on its way to the GC...

The exception to this rule is a class type that has complete value semantics, like System.String.