rspec/rules/S3962/csharp/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
Inline adoc files when they are included exactly once.

Also fix language tags because this inlining gives us better information
on what language the code is written in.
2023-05-25 14:18:12 +02:00

81 lines
1.4 KiB
Plaintext

== Why is this an issue?
The value of a ``++static readonly++`` field is computed at runtime while the value of a ``++const++`` field is calculated at compile time, which improves performance.
This rule raises an issue when a ``++static readonly++`` field is initialized with a value that is computable at compile time.
As specified by Microsoft, the list of types that can have a constant value are:
[frame=all]
[cols="^1,^1"]
|===
|C# type|.Net Fwk type
|bool|System.Boolean
|byte|System.Byte
|sbyte|System.SByte
|char|System.Char
|decimal|System.Decimal
|double|System.Double
|float|System.Single
|int|System.Int32
|uint|System.UInt32
|long|System.Int64
|ulong|System.UInt64
|short|System.Int16
|ushort|System.UInt16
|string|System.String
|===
=== Noncompliant code example
[source,csharp]
----
namespace myLib
{
public class Foo
{
static readonly int x = 1; // Noncompliant
static readonly int y = x + 4; // Noncompliant
static readonly string s = "Bar"; // Noncompliant
}
}
----
=== Compliant solution
[source,csharp]
----
namespace myLib
{
public class Foo
{
const int x = 1;
const int y = x + 4;
const string s = "Bar";
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Replace this "static readonly" declaration with "const".
=== Highlighting
the field declaration
endif::env-github,rspecator-view[]