2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-01-27 13:42:22 +01:00
Marking a variable that is unchanged after initialization ``++const++`` is an indication to future maintainers that "no this isn't updated, and it's not supposed to be". ``++const++`` should be used in these situations in the interests of code clarity.
2020-06-30 12:48:39 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2020-06-30 12:48:39 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:48:39 +02:00
----
public bool Seek(int[] input)
{
2022-09-07 13:31:52 +02:00
var target = 32; // Noncompliant
2020-06-30 12:48:39 +02:00
foreach (int i in input)
{
if (i == target)
{
return true;
}
}
return false;
}
----
2022-09-07 13:31:52 +02:00
or
[source,csharp]
----
public class Sample
{
public void Method()
{
var context = $"{nameof(Sample)}.{nameof(Method)}"; // Noncompliant (C# 10 and above only)
}
}
----
2020-06-30 12:48:39 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2020-06-30 12:48:39 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:48:39 +02:00
----
public bool Seek(int[] input)
{
const int target = 32;
foreach (int i in input)
{
if (i == target)
{
return true;
}
}
return false;
}
----
2022-09-07 13:31:52 +02:00
or
[source,csharp]
----
public class Sample
{
public void Method()
{
const string context = $"{nameof(Sample)}.{nameof(Method)}";
}
}
----
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
Add the 'const' modifier to 'xxx'.
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]