== Why is this an issue?

Properties provide a way to enforce https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)[encapsulation] by providing accessors that give controlled access to `private` fields. However, in classes with multiple fields, it is not unusual that https://en.wikipedia.org/wiki/Copy-and-paste_programming[copy-and-paste] is used to quickly create the needed properties, which can result in the wrong field being accessed by a getter or setter.

[source,csharp]
----
class C
{
    private int x;
    private int y;
    public int Y => x; // Noncompliant: The returned field should be 'y'
}
----

This rule raises an issue in any of these cases:

* A getter does not access the field with the corresponding name.
* A setter does not update the field with the corresponding name.

For simple properties, it is better to use https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties[auto-implemented properties] (C# 3.0 or later).

Field and property names are compared as case-insensitive. All underscore characters are ignored.

== How to fix it

=== Code examples

==== Noncompliant code example

[source,csharp,diff-id=1,diff-type=noncompliant]
----
class A
{
    private int x;
    private int y;

    public int X
    {
        get { return x; }
        set { x = value; }
    }

    public int Y
    {
        get { return x; }  // Noncompliant: field 'y' is not used in the return value
        set { x = value; } // Noncompliant: field 'y' is not updated
    }
}
----

==== Compliant solution

[source,csharp,diff-id=1,diff-type=compliant]
----
class A
{
    private int x;
    private int y;

    public int X
    {
        get { return x; }
        set { x = value; }
    }

    public int Y
    {
        get { return y; }
        set { y = value; }
    }
}
----

== Resources

* Microsoft Learn: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties[Properties (C# Programming Guide)]

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

include::../message.adoc[]

include::../highlighting.adoc[]

endif::env-github,rspecator-view[]
