rspec/rules/S3962/csharp/rule.adoc

81 lines
1.4 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
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
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
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
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
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[]