2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
Fields and auto-properties that are never assigned to hold the default values for their types. They are either pointless code or, more likely, mistakes.
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
----
class MyClass
{
private int field; // Noncompliant, shouldn't it be initialized? This way the value is always default(int), 0.
private int Property { get; set; } // Noncompliant
public void Print()
{
Console.WriteLine(field); //Will always print 0
Console.WriteLine(Property); //Will always print 0
}
}
----
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
----
class MyClass
{
private int field = 1;
private int Property { get; set; } = 42;
public void Print()
{
field++;
Console.WriteLine(field);
Console.WriteLine(Property);
}
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Exceptions
2022-03-14 13:22:38 +01:00
* Fields on types decorated with `System.SerializableAttribute` attribute.
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Remove unassigned [auto-property|field] "xxx", or set its value.
=== Highlighting
property/field name
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== supercedes: S2332
=== on 10 Dec 2015, 15:51:43 Ann Campbell wrote:
Please supply code samples [~tamas.vajk]
=== on 11 Dec 2015, 08:45:55 Tamas Vajk wrote:
\[~ann.campbell.2] WDYT?
=== on 11 Dec 2015, 13:57:33 Ann Campbell wrote:
Looks good
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]