rspec/rules/S1104/csharp/rule.adoc

101 lines
2.3 KiB
Plaintext

== Why is this an issue?
include::../description.adoc[]
Note that due to optimizations on simple properties, public fields provide only very little performance gain.
include::../impacts.adoc[]
=== Exceptions
Fields marked as `readonly` or `const` are ignored by this rule.
Fields inside classes or structs annotated with `[StructLayout]` are ignored by this rule.
Fields inside classes or structs annotated with `[Serializable]` are ignored by this rule unless they are annotated with `[NonSerialized]`.
== How to fix it
Depending on your needs:
* Use auto-implemented properties: +
For common cases, where no validation is required, auto-implemented properties are a good alternative to fields: these allows fine grained access control and offers the flexibility to add validation or change internal storage afterwards.
__Note:__ as a bonus it is now possible to monitor value changes using breakpoints.
* Encapsulate the fields in your class. To do so:
. Make the field private.
. Use public properties (set and get) to access and modify the field.
* Mark field as `readonly` or `const`.
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
----
public class Foo
{
public int InstanceData = 32; // Noncompliant
public int AnotherInstanceData = 32; // Noncompliant
}
----
==== Compliant solution
[source,csharp,diff-id=1,diff-type=compliant]
----
public class Foo
{
// using auto-implemented properties
public int InstanceData { get; set; } = 32;
// using field encapsulation
private int _anotherInstanceData = 32;
public int AnotherInstanceData
{
get { return _anotherInstanceData; }
set
{
// perform validation
_anotherInstanceData = value;
}
}
}
----
=== Pitfalls
Please be aware that changing a field by a property in a software that uses serialization could lead to binary incompatibility.
include::../see.adoc[]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Make this field 'private' and encapsulate it in a 'public' property.
=== Highlighting
Field identifier.
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]