diff --git a/ChangeLog.md b/ChangeLog.md index 4275a182f0..4a6088883f 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [CLI] Fix loading of `slnf` files ([PR](https://github.com/dotnet/roslynator/pull/1447)) - [CLI] Fix `--severity-level` ([PR](https://github.com/dotnet/roslynator/pull/1449)) +- Fix analyzer [RCS1246](https://josefpihrt.github.io/docs/roslynator/analyzers/RCS1246) ([PR](https://github.com/dotnet/roslynator/pull/1451)) ## [4.12.1] - 2024-04-15 diff --git a/src/Core/SymbolUtility.cs b/src/Core/SymbolUtility.cs index 166b7fea9e..06b3130a5c 100644 --- a/src/Core/SymbolUtility.cs +++ b/src/Core/SymbolUtility.cs @@ -121,6 +121,9 @@ public static bool IsEventHandlerMethod(IMethodSymbol methodSymbol) return hasIndexer.Value; } + if (originalDefinition.EqualsOrInheritsFrom(MetadataNames.System_Collections_Generic_List_T)) + return true; + if (originalDefinition.ImplementsAny( SpecialType.System_Collections_Generic_IList_T, SpecialType.System_Collections_Generic_IReadOnlyList_T, diff --git a/src/Tests/Analyzers.Tests/RCS1246UseElementAccessTests.cs b/src/Tests/Analyzers.Tests/RCS1246UseElementAccessTests.cs index 8ebbf97d4e..6f84f80c7d 100644 --- a/src/Tests/Analyzers.Tests/RCS1246UseElementAccessTests.cs +++ b/src/Tests/Analyzers.Tests/RCS1246UseElementAccessTests.cs @@ -40,6 +40,36 @@ void M() ", source, expected); } + [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseElementAccess)] + public async Task Test_UseElementAccessInsteadOfFirst_DerivedFromList() + { + await VerifyDiagnosticAndFixAsync(@" +using System.Linq; +using System.Collections.Generic; + +class C : List +{ + void M() + { + var list = new C(); + var x = list.[|First()|]; + } +} +", @" +using System.Linq; +using System.Collections.Generic; + +class C : List +{ + void M() + { + var list = new C(); + var x = list[0]; + } +} +"); + } + [Theory, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseElementAccess)] [InlineData("((List)x).[|ElementAt(1)|]", "((List)x)[1]")] [InlineData("((IList)x).[|ElementAt(1)|]", "((IList)x)[1]")] @@ -68,6 +98,36 @@ void M() ", source, expected); } + [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseElementAccess)] + public async Task Test_UseElementAccessInsteadOfElementAt_DerivedFromList() + { + await VerifyDiagnosticAndFixAsync(@" +using System.Linq; +using System.Collections.Generic; + +class C : List +{ + void M() + { + var list = new C(); + var x = list.[|ElementAt(1)|]; + } +} +", @" +using System.Linq; +using System.Collections.Generic; + +class C : List +{ + void M() + { + var list = new C(); + var x = list[1]; + } +} +"); + } + [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseElementAccess)] public async Task TestNoDiagnostic_UseElementAccessInsteadOfElementAt() {