Analyzer request: warn on declaration of local variable with duplicate name conflict
- Dominant language
- C#
- Stars
- 3.5k
- Forks
- 294
- Avg merge
- 2h 30m
- Merged PRs (30d)
- 4
Description
The C# language permits declaring a local variable with the same name as a field or property of that class. It overrides it's meaning in the scope of that method. Some time ago I tried to use the new `is` pattern matching functionality in this elaborate sample:
```csharp
void Main()
{
var c = new MyClass();
c.TestString("Changed");
Console.WriteLine($"LocalField: {c.LocalField}");
// LocalField: Default
}
// Define other methods and classes here
public class MyClass
{
private string localField = "Default";
public string LocalField => localField;
public bool TestString(object o)
{
// this line defines a new variable with same name as class field
if (o is string localField)
return true;
return false;
}
public void Test()
{
// this line defines a new variable with same name as class field
string localField = "MyValue";
}
}
```
Admittedly using proper naming conventions in a project and abiding by them, would probably help preventing this somewhat but it can still happen. I think I'd would be beneficial to warn/hint on declaring local variables with the same name as class fields/properties in the same scope. It is something that is definitely permitted but (in my opinion) ill-advised in production code.
The analyzer should detect both samples above and others, like pattern matching inside a `switch`.
Contributor guide
Assessment
This issue has not been assessed yet.