2023-05-03 11:06:20 +02:00
== 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:
2021-06-03 16:43:28 +02:00
[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
|===
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== 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
}
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== 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";
}
}
----
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Replace this "static readonly" declaration with "const".
=== Highlighting
the field declaration
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]