CS.MAGIC.STRING
Magic number used: string.
Magic numbers are used. This checker checks variable declarations, method arguments, and the use of magic numbers in binary operations.
Vulnerability and risk
The use of magic numbers impairs maintainability.
Mitigation and prevention
Use the const or readonly qualifier to declare constant variables.
Example
Copy
using System;
namespace kmcustom
{
public class C11
{
double d314 = 3.14; //NG
int i0 = 0;//OK
int i1 = 1;//OK
int i2 = 2;//NG
decimal dec2 = 2;//NG
float float2 = 2.0F;//NG
uint uint2 = 2;//NG
short short2 = 2;//NG
ushort ushort2 = 2;//NG
long long2 = 2;//NG
ulong ulong2 = 2;//NG
const int const_i2 = 2;//OK
static readonly int static_readonly_i2 = 2;//OK
int assign_const_i2 = const_i2;//OK
int assign_const_i2_and_magicnum = const_i2 + 3;//NG
char c1 = '1';//NG
const char const_c1 = '1';//OK
String s1 = "string1";//NG
const String sf1 = "string1";//OK
const double fDB314 = 3.14;//OK
double var_init_with_const = fDB314;
public void somefunc_number(double a, int b)
{
}
public void somefunc_char(char str)
{
}
public void somefunc_string(String str)
{
}
public void test_number(int v, String strVar)
{
double local_var = 3.14;//NG
if (v < 3)//NG
{
somefunc_number(v, 2);//NG
somefunc_number(3.1, v);//NG
somefunc_number(v, v);//OK
}
if (0 != v)//NG
{
}
}
public void test_char(char v)
{
char local_var = 'a';//NG
const char const_local_var = 'a';//OK
if (v != '3')
{//NG
somefunc_char('a');//NG
somefunc_char(v);//OK
}
if ('0' != v)//NG
{
}
}
public void test_string(String v)
{
String local_var = "a";//NG
const String const_local_var = "fix";//OK
if (v.Length != "3".Length) //NG
{
somefunc_string("a");//NG
somefunc_string(v);//OK
}
if ("0".Length != v.Length)//NG
{
}
}
}
}