Playing with SonarQube Version 7.6 (build 21501) SonarQube scanners with MSBuild and sonar lint did not find any magic numbers (and duplicated code).
I made a custom quality profile with all rules enabled for .NET.
Below you’ll find the following:
- Part of ruleset,
- warnings in visual studio
- code .
S109 is available in the ruleset.
<Rule Id="S106" Action="Warning" />
<Rule Id="S109" Action="Warning" />
<Rule Id="S108" Action="Warning" />
Sonar warnings raised on the code:
Severity Code Description Project File Line Suppression State Detail Description
Warning S131 Add a ‘default’ clause to this ‘switch’ statement. TestMagicNumbers \TestMagicNumbers\TestMagicNumbers\Program.cs 42 Active
Warning S131 Add a ‘default’ clause to this ‘switch’ statement. TestMagicNumbers \TestMagicNumbers\TestMagicNumbers\Program.cs 67 Active
Warning S1118 Add a ‘protected’ constructor or the ‘static’ keyword to the class declaration. TestMagicNumbers \TestMagicNumbers\TestMagicNumbers\Program.cs 10 Active Utility classes, which are collections of static members, are not meant to be instantiated.
Warning S1118 Add a ‘protected’ constructor or the ‘static’ keyword to the class declaration. TestMagicNumbers \TestMagicNumbers\TestMagicNumbers\Program.cs 31 Active
Warning S113 Add a new line at the end of the file ‘Program.cs’. TestMagicNumbers \TestMagicNumbers\TestMagicNumbers\Program.cs 95 Active
Warning S1451 Add or update the header of this file. TestMagicNumbers \TestMagicNumbers\TestMagicNumbers\Program.cs 1 Active
Warning S4056 Use the overload that takes a ‘CultureInfo’ or ‘IFormatProvider’ parameter. TestMagicNumbers \TestMagicNumbers\TestMagicNumbers\Program.cs 35 Active
Code .NET Framework 4.7.2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace TestMagicNumbers
{
public class TestClass
{
public static int TestFunction(int a)
{
switch (a)
{
case 1:
return 3;
case 2:
return 4;
case 3:
return 6;
default:
return 7;
}
}
}
internal class Program
{
private static void Main(string[] args)
{
var aValue = int.Parse(args[0]);
TestClass.TestFunction(12);
if (aValue < 3)
{
Console.WriteLine("dag");
}
switch (aValue)
{
case 1:
Console.WriteLine("1");
break;
case 2:
Console.WriteLine("2");
break;
case 3:
Console.WriteLine("3");
break;
case 4:
Console.WriteLine("4");
break;
}
Test(aValue);
DoSomething();
}
private static void Test(int getal)
{
switch (getal)
{
case 1:
Console.WriteLine("1");
break;
case 2:
Console.WriteLine("2");
break;
case 3:
Console.WriteLine("3");
break;
case 4:
Console.WriteLine("4");
break;
}
}
public static void DoSomething()
{
for (int i = 0; i < 4; i++) // Noncompliant, 4 is a magic number
{
Console.WriteLine(i);
}
}
}
}