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

Rule:  10@301Checked automatically with code checker

Synopsis:Do not use 'magic numbers'
Language:C#
Severity Level:7
Category:Data types


Description:

Do not use literal values, either numeric or strings, in your code other than to define symbolic constants. Use the following pattern to define constants:

public class Whatever
{
	public static readonly Color PapayaWhip = new Color(0xFFEFD5);
	public const int MaxNumberOfWheels = 18;
}

Strings intended for logging or tracing are exempt from this rule.

Literals are allowed when their meaning is clear from the context, and not subject to future changes. For instance, the values 0, 1 and 2 can be used safely. The same holds for mathematical angels 90, 180, 270 and 360, powers of 2 and powers of 10.

mean = (a + b) / 2;					// okay
WaitMilliseconds(waitTimeInSeconds * 1000);		// clear enough

If the value of one constant depends on the value of another, do attempt to make this explicit in the code, so do not write

public class SomeSpecialContainer
{
	public const int MaxItems = 32;
	public const int HighWaterMark = 24;	// at 75%
	...
}

but rather do write

public class SomeSpecialContainer
{
	public const int MaxItems = 32;
	public const int HighWaterMark = 3 * MaxItems / 4;	// at 75%
	...
}

Please note that an enum can often be used for certain types of symbolic constants.