
The languages for this rule fall into two categories: * CFamily, JS, and PLSQL: "Variables should not be shadowed" (general case of shadowing) * C#, Flex, Java, PHP, Swift: "Local variables should not shadow field/property/enum case/..." (narrow case of shadowing) For CFamily, these tickets are also handled: CPP-2785 CPP-3589
42 lines
1.2 KiB
Plaintext
42 lines
1.2 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Shadowing occurs when a local variable has the same name as a variable, field, or property in an outer scope.
|
|
|
|
include::../problems.adoc[]
|
|
|
|
To avoid these problems, rename the shadowing, shadowed, or both variables/fields/properties to accurately represent their purpose with unique and meaningful names.
|
|
It improves clarity and allows reasoning locally about the code without considering other software parts.
|
|
|
|
This rule focuses on variables shadowing fields or properties.
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,csharp]
|
|
----
|
|
class Foo
|
|
{
|
|
public int myField;
|
|
public int MyProperty { get; set; }
|
|
|
|
public void DoSomething()
|
|
{
|
|
int myField = 0; // Noncompliant
|
|
int MyProperty = 0; // Noncompliant
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/fields[Fields]
|
|
* Microsoft Learn - https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties[Properties]
|
|
|
|
=== Related rules
|
|
|
|
* S2387 - Child class fields should not shadow parent class fields
|
|
* S3218 - Inner class members should not shadow outer class "static" or type members
|
|
|
|
include::../rspecator.adoc[]
|