Skip to content

Commit

Permalink
Fix RCS1246 (#1451)
Browse files Browse the repository at this point in the history
  • Loading branch information
josefpihrt committed Apr 23, 2024
1 parent 9247ccc commit 4a8e1a1
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions ChangeLog.md
Expand Up @@ -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

Expand Down
3 changes: 3 additions & 0 deletions src/Core/SymbolUtility.cs
Expand Up @@ -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,
Expand Down
60 changes: 60 additions & 0 deletions src/Tests/Analyzers.Tests/RCS1246UseElementAccessTests.cs
Expand Up @@ -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<string>
{
void M()
{
var list = new C();
var x = list.[|First()|];
}
}
", @"
using System.Linq;
using System.Collections.Generic;
class C : List<string>
{
void M()
{
var list = new C();
var x = list[0];
}
}
");
}

[Theory, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseElementAccess)]
[InlineData("((List<object>)x).[|ElementAt(1)|]", "((List<object>)x)[1]")]
[InlineData("((IList<object>)x).[|ElementAt(1)|]", "((IList<object>)x)[1]")]
Expand Down Expand Up @@ -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<string>
{
void M()
{
var list = new C();
var x = list.[|ElementAt(1)|];
}
}
", @"
using System.Linq;
using System.Collections.Generic;
class C : List<string>
{
void M()
{
var list = new C();
var x = list[1];
}
}
");
}

[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.UseElementAccess)]
public async Task TestNoDiagnostic_UseElementAccessInsteadOfElementAt()
{
Expand Down

0 comments on commit 4a8e1a1

Please sign in to comment.