MagicNumberAnalyser 3.0.9

The owner has unlisted this package. This could mean that the package is deprecated, has security vulnerabilities or shouldn't be used anymore.
dotnet add package MagicNumberAnalyser --version 3.0.9
                    
NuGet\Install-Package MagicNumberAnalyser -Version 3.0.9
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MagicNumberAnalyser" Version="3.0.9">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MagicNumberAnalyser" Version="3.0.9" />
                    
Directory.Packages.props
<PackageReference Include="MagicNumberAnalyser">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add MagicNumberAnalyser --version 3.0.9
                    
#r "nuget: MagicNumberAnalyser, 3.0.9"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package MagicNumberAnalyser@3.0.9
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=MagicNumberAnalyser&version=3.0.9
                    
Install as a Cake Addin
#tool nuget:?package=MagicNumberAnalyser&version=3.0.9
                    
Install as a Cake Tool

MagicNumberAnalyser

Analisador Roslyn que detecta magic numbers em código C# e os reporta como warnings, incentivando o uso de constantes nomeadas para melhor legibilidade e manutenibilidade.

Diagnóstico

  • ID: MAGIC_NUMBER_ISSUE
  • Categoria: Maintainability
  • Severidade: Warning

Instalação

dotnet add package MagicNumberAnalyser

O que detecta

Literais numéricos (exceto 0 e 1) usados diretamente em expressões onde o propósito do valor não é claro pelo contexto.

Exemplos não conformes

if (value > 255) { }

for (int i = 0; i < 52; i++) { }

var tax = subtotal * 0.21m;

Exemplos conformes (excluídos automaticamente)

O analisador é sensível ao contexto e ignora literais numéricos onde o código ao redor já fornece significado:

// Constantes — já nomeadas
const int MaxRetries = 3;
private const double Pi = 3.14159;

// Membros de enum
enum Status { Active = 1, Inactive = 2 }

// Atributos
[StringLength(50)]
[Range(1, 100)]

// Inicializadores de objeto/coleção — o nome da propriedade fornece contexto
var person = new Person { Age = 30, Score = 95.5 };

// Inicializadores de array/coleção
var codes = new[] { 200, 301, 404 };
var list = new List<int> { 1, 2, 3 };

// Argumentos de método e construtor — o nome do parâmetro fornece contexto
var date = new DateTime(2024, 1, 1);
Math.Round(value, 2);

// Valores padrão de parâmetro
void Fetch(int timeout = 30, int retries = 3) { }

// Tamanhos de array
var buffer = new byte[1024];

// Property patterns
var isDefault = url is { Port: 80 };

// Inicializadores de propriedade
public int MaxRedirects { get; set; } = 10;

// Declarações de variável — o nome da variável fornece contexto
var statusCode = 302;
int timeout = 5000;

// 0 e 1 são sempre permitidos (todos os tipos numéricos)

Pacote complementar

Para extração automática de magic numbers para constantes nomeadas com nomes sugeridos por IA, veja MagicNumberCodeFix. O CodeFix permite configurar o modelo de IA e o estilo de nomenclatura (PascalCase ou SCREAMING_SNAKE_CASE) via arquivo de configuração.

Suprimindo warnings

#pragma warning disable MAGIC_NUMBER_ISSUE
var value = 42;
#pragma warning restore MAGIC_NUMBER_ISSUE

Ou no .editorconfig:

[*.cs]
dotnet_diagnostic.MAGIC_NUMBER_ISSUE.severity = none

Licença

MIT

There are no supported framework assets in this package.

Learn more about Target Frameworks and .NET Standard.

This package has no dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated