rspec/rules/S3962/csharp/rule.adoc

71 lines
1.1 KiB
Plaintext
Raw Normal View History

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:
||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 16:49:39 +02:00
== Noncompliant Code Example
----
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 16:49:39 +02:00
== Compliant Solution
----
namespace myLib
{
public class Foo
{
const int x = 1;
const int y = x + 4;
const string s = "Bar";
}
}
----