├── .editorconfig ├── .gitignore ├── Documentation ├── img │ ├── string-example-1.gif │ ├── string-example-2.png │ └── enumerable-example-1.gif ├── CI0006.md ├── CI0002.md ├── CI0004.md ├── CI0007.md ├── CI0005.md ├── CI0008.md ├── CI0001.md ├── Diagnostics.md └── CI0003.md ├── Collections.Analyzer ├── Diagnostics │ ├── Categories.cs │ ├── ExpressionExtensions.cs │ ├── CI0003 │ │ ├── AddRangeDiagnostic.cs │ │ ├── StringJoinToArrayDiagnostic.cs │ │ ├── AssignEnumerableDiagnostic.cs │ │ ├── ObjectInitializerDiagnostic.cs │ │ ├── ConstructorDiagnostic.cs │ │ └── EnumerableToArrayOnReturnDiagnostic.cs │ ├── StringExtensions.cs │ ├── CI0005 │ │ └── ToArrayLengthDiagnostic.cs │ ├── CI0002 │ │ └── ArrayToArrayDiagnostic.cs │ ├── CI0006 │ │ └── ListInitializerDiagnostic.cs │ ├── CI0007 │ │ └── ConcurrentCollectionIsEmptyDiagnostic.cs │ ├── CI0001 │ │ └── StringToArrayDiagnostic.cs │ └── CI0004 │ │ └── ListFromStringDiagnostic.cs ├── Collections.Analyzer.csproj ├── CodeFixes │ ├── ReplaceWithCountCodeFix.cs │ ├── AddToCharArrayCodeFix.cs │ ├── ReplaceAnyWithIsEmptyCodeFix.cs │ ├── SetListCapacityCodeFix.cs │ └── RemoveRedundantMethodCallCodeFix.cs ├── Resources.ru.resx └── Resources.resx ├── Tests ├── Resources │ ├── ArrayContains7.txt │ ├── ArrayContains3.txt │ ├── ArrayContains2.txt │ ├── ArrayContains1.txt │ ├── ArrayContains4.txt │ ├── ArrayContainsBefore3.txt │ ├── ArrayContainsBefore2.txt │ ├── ArrayContainsBefore1.txt │ ├── ArrayContainsBefore4.txt │ ├── ArrayContains6.txt │ ├── ListInitializer1.txt │ ├── ArrayContains5.txt │ ├── ListInitializer2.txt │ ├── ListInitializerAfter1.txt │ ├── ListInitializerAfter2.txt │ ├── ArrayContainsAfter3.txt │ ├── ListInitializerBefore1.txt │ ├── ListInitializerBefore2.txt │ ├── ArrayContainsAfter1.txt │ ├── ArrayContainsAfter2.txt │ ├── SelectStringToArray.txt │ ├── ArrayContainsAfter4.txt │ ├── ListCountAfter.txt │ ├── ArrayToArrayAfter.txt │ ├── EnumerablePropertyToArray.txt │ ├── StringJoinAfter.txt │ ├── ArrayToArray.txt │ ├── StringJoin1.txt │ ├── ArrayCountAfter.txt │ ├── ListCountBefore.txt │ ├── ArrayToArrayBefore.txt │ ├── StringJoinBefore.txt │ ├── StringListConstructor2.txt │ ├── ArrayCountBefore.txt │ ├── EnumerableMethodToArray.txt │ ├── StringListConstructorBefore2.txt │ ├── StringListConstructor1.txt │ ├── StringListConstructorAfter.txt │ ├── ForeachStringToCharArrayAfter.txt │ ├── StringListConstructorBefore1.txt │ ├── ForeachStringToCharArray.txt │ ├── AssignEnumerableAfter2.txt │ ├── AddRangeAfter.txt │ ├── AssignEnumerable1.txt │ ├── ConcurrentBag1.txt │ ├── AddRange1.txt │ ├── ConcurrentBagAfter1.txt │ ├── ConcurrentBagAfter4.txt │ ├── ConcurrentQueue1.txt │ ├── ConcurrentStack1.txt │ ├── ForeachStringToCharArrayBefore.txt │ ├── AssignEnumerableBefore2.txt │ ├── ConcurrentBag3.txt │ ├── ConcurrentQueueAfter1.txt │ ├── ConcurrentQueueAfter4.txt │ ├── ConcurrentStackAfter1.txt │ ├── ConcurrentStackAfter4.txt │ ├── AddRangeBefore.txt │ ├── ConcurrentBagBefore1.txt │ ├── ConcurrentBagBefore4.txt │ ├── ConcurrentQueue3.txt │ ├── ConcurrentStack3.txt │ ├── ForeachStringToArrayAfter.txt │ ├── ForeachStringToListAfter.txt │ ├── ConcurrentQueueBefore1.txt │ ├── ConcurrentQueueBefore4.txt │ ├── ConcurrentStackBefore1.txt │ ├── ConcurrentStackBefore4.txt │ ├── ForeachStringToArray.txt │ ├── GetArrayToArrayAfter.txt │ ├── ForeachStringToListBefore.txt │ ├── GetArrayToArray.txt │ ├── GetStringSelectToArray.txt │ ├── GetStringToCharArraySelectAfter.txt │ ├── ForeachStringToArrayBefore.txt │ ├── GetSetToArray.txt │ ├── AssignEnumerableAfter1.txt │ ├── AsyncEnumerableMethodToArray2.txt │ ├── GetArrayToArrayBefore.txt │ ├── AssignEnumerable2.txt │ ├── ConcurrentDictionary1.txt │ ├── GetStringToCharArraySelectBefore.txt │ ├── AssignEnumerableBefore1.txt │ ├── ConcurrentDictionaryAfter1.txt │ ├── ConcurrentDictionaryAfter4.txt │ ├── AddRange2.txt │ ├── ConcurrentDictionaryBefore1.txt │ ├── ConcurrentDictionaryBefore4.txt │ ├── AsyncEnumerableMethodToArray.txt │ ├── ConcurrentBag2.txt │ ├── ConcurrentDictionary2.txt │ ├── ConcurrentBagAfter2.txt │ ├── ConcurrentQueue2.txt │ ├── ConcurrentStack2.txt │ ├── ConcurrentBagBefore2.txt │ ├── ConcurrentQueueAfter2.txt │ ├── ConcurrentStackAfter2.txt │ ├── ConcurrentQueueBefore2.txt │ ├── ConcurrentStackBefore2.txt │ ├── ConcurrentBagAfter3.txt │ ├── ConcurrentQueueAfter3.txt │ ├── ConcurrentStackAfter3.txt │ ├── ConcurrentBagBefore3.txt │ ├── ConcurrentQueueBefore3.txt │ ├── ConcurrentStackBefore3.txt │ ├── ConcurrentDictionary3.txt │ ├── ConcurrentDictionaryAfter2.txt │ ├── ConcurrentDictionaryBefore2.txt │ ├── ConcurrentDictionaryAfter3.txt │ ├── Constructor4.txt │ ├── ConcurrentDictionaryBefore3.txt │ ├── Constructor1.txt │ ├── ObjectInitializerAfter.txt │ ├── ObjectInitializer.txt │ ├── ObjectInitializerBefore.txt │ ├── ConstructorAfter.txt │ ├── Constructor2.txt │ ├── Constructor3.txt │ └── ConstructorBefore.txt ├── ArrayTests │ ├── AddRangeVerifier.cs │ ├── ConstructorVerifier.cs │ ├── ObjectInitializerVerifier.cs │ ├── RedundantArrayToArrayConversionVerifier.cs │ ├── ObjectInitializerTests.cs │ ├── AddRangeTests.cs │ ├── RedundantArrayToArrayConversionTests.cs │ └── ConstructorTests.cs ├── StringTests │ ├── ListFromStringVerifier.cs │ ├── StringJoinToArrayConversionVerifier.cs │ ├── RedundantStringToArrayConversionVerifier.cs │ ├── StringJoinToArrayConversionTests.cs │ ├── ListFromStringTests.cs │ └── RedundantStringToArrayConversionTests.cs ├── ListTests │ ├── ListCapacityVerifier.cs │ └── ListCapacityTests.cs ├── EnumerableTests │ ├── AssignEnumerableVerifier.cs │ ├── RedundantEnumerableToArrayConversionVerifier.cs │ ├── AssignEnumerableTests.cs │ └── RedundantEnumerableToArrayConversionTests.cs ├── ArrayLengthTests │ ├── RedundantToArrayLengthVerifier.cs │ └── RedundantToArrayLengthTests.cs ├── ArrayContainsToHashSetTests │ ├── ArrayContainsVerifier.cs │ └── ArrayContainsToHashSetTests.cs ├── ConcurrentBagIsEmptyTests │ ├── ConcurrentBagIsEmptyVerifier.cs │ └── IsEmptyTests.cs ├── ConcurrentQueueIsEmptyTests │ ├── ConcurrentQueueIsEmptyVerifier.cs │ └── IsEmptyTests.cs ├── ConcurrentStackIsEmptyTests │ ├── ConcurrentQueueIsEmptyVerifier.cs │ └── IsEmptyTests.cs ├── ConcurrentDictionaryIsEmptyTests │ ├── ConcurrentDictionaryIsEmptyVerifier.cs │ └── IsEmptyTests.cs └── ResourceReader.cs ├── Benchmarks ├── Program.cs ├── Benchmarks.csproj ├── ArrayToArrayBenchmark.cs ├── AddRangeBenchmark.cs ├── InitListBenchmark.cs └── ConcurrentCollectionsBenchmark.cs ├── Examples ├── HashSets │ └── DistinctToArray.cs ├── Strings │ ├── Constructor.cs │ ├── Join.cs │ ├── Foreach.cs │ └── LinqMethods.cs ├── Examples.csproj ├── Enumerable │ ├── AssignEnumerable.cs │ ├── AddRange.cs │ ├── Count.cs │ ├── Constructor.cs │ └── ReturnArray.cs ├── ConcurrentCollections │ ├── ConcurrentQueueIsEmpty.cs │ ├── ConcurrentStackIsEmpty.cs │ ├── ConcurrentDictionaryIsEmpty.cs │ └── ConcurrentBagIsEmpty.cs └── Arrays │ ├── ArrayContains.cs │ └── ArrayToArray.cs ├── .github └── workflows │ └── publish.yml ├── LICENSE ├── CHANGELOG.md ├── README.md └── Collections.Analyzer.sln /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*.cs] 4 | indent_style = space 5 | indent_size = 4 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | obj/ 3 | /packages/ 4 | riderModule.iml 5 | /_ReSharper.Caches/ 6 | /.idea 7 | /.vs 8 | *.DotSettings.user -------------------------------------------------------------------------------- /Documentation/img/string-example-1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backs/Collections.Analyzer/HEAD/Documentation/img/string-example-1.gif -------------------------------------------------------------------------------- /Documentation/img/string-example-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backs/Collections.Analyzer/HEAD/Documentation/img/string-example-2.png -------------------------------------------------------------------------------- /Documentation/img/enumerable-example-1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Backs/Collections.Analyzer/HEAD/Documentation/img/enumerable-example-1.gif -------------------------------------------------------------------------------- /Collections.Analyzer/Diagnostics/Categories.cs: -------------------------------------------------------------------------------- 1 | namespace Collections.Analyzer.Diagnostics 2 | { 3 | internal static class Categories 4 | { 5 | public static readonly string Performance = "Performance"; 6 | } 7 | } -------------------------------------------------------------------------------- /Tests/Resources/ArrayContains7.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | class TestClass 4 | { 5 | void TestMethod() 6 | { 7 | var numbers = new[] { 1, 2, 3, 4, 5 }; 8 | var sum = numbers.Sum(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Tests/Resources/ArrayContains3.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | class TestClass 4 | { 5 | private readonly int[] _list2 = { 1, 2, 3, 4 }; 6 | 7 | public bool Method() 8 | { 9 | return _list2.Contains(5); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Benchmarks/Program.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Running; 2 | using Benchmarks; 3 | 4 | internal class Program 5 | { 6 | public static void Main(string[] args) 7 | { 8 | BenchmarkRunner.Run(); 9 | } 10 | } -------------------------------------------------------------------------------- /Tests/Resources/ArrayContains2.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | class TestClass 4 | { 5 | private readonly int[] _list2 = new int[] { 1, 2, 3, 4 }; 6 | 7 | public bool Method() 8 | { 9 | return _list2.Contains(5); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Tests/Resources/ArrayContains1.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | class TestClass 4 | { 5 | void TestMethod() 6 | { 7 | var numbers = new[] { 1, 2, 3, 4, 5 }; 8 | if (numbers.Contains(3)) 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Tests/Resources/ArrayContains4.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | class TestClass 4 | { 5 | public int[] List3 { get; } = new[] { 1, 2, 3, 4 }; 6 | 7 | public bool Check(int value) 8 | { 9 | return List3.Contains(value); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Tests/Resources/ArrayContainsBefore3.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | class TestClass 4 | { 5 | private readonly int[] {|CI0008:_list2|} = { 1, 2, 3, 4 }; 6 | 7 | public bool Method() 8 | { 9 | return _list2.Contains(5); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Tests/Resources/ArrayContainsBefore2.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | class TestClass 4 | { 5 | private readonly int[] {|CI0008:_list2|} = new int[] { 1, 2, 3, 4 }; 6 | 7 | public bool Method() 8 | { 9 | return _list2.Contains(5); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Tests/Resources/ArrayContainsBefore1.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | class TestClass 4 | { 5 | void TestMethod() 6 | { 7 | var {|CI0008:numbers|} = new[] { 1, 2, 3, 4, 5 }; 8 | if (numbers.Contains(3)) 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Tests/Resources/ArrayContainsBefore4.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | class TestClass 4 | { 5 | public int[] {|CI0008:List3|} { get; } = new[] { 1, 2, 3, 4 }; 6 | 7 | public bool Check(int value) 8 | { 9 | return List3.Contains(value); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Tests/Resources/ArrayContains6.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | class TestClass 4 | { 5 | void TestMethod() 6 | { 7 | var numbers = new[] { 1, 2, 3, 4, 5 }; 8 | if (numbers.Contains(3)) 9 | { 10 | } 11 | numbers[0] = 10; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Tests/Resources/ListInitializer1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Examples.Lists 4 | { 5 | public class ListInitializer 6 | { 7 | public void Method1() 8 | { 9 | var list1 = new List {1, 2, 3, 4}; 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Tests/Resources/ArrayContains5.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | class TestClass 4 | { 5 | void TestMethod() 6 | { 7 | var numbers = new[] { 1, 2, 3, 4, 5 }; 8 | if (numbers.Contains(3)) 9 | { 10 | } 11 | var first = numbers[0]; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Tests/Resources/ListInitializer2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Examples.Lists 4 | { 5 | public class ListInitializer 6 | { 7 | public void Method1() 8 | { 9 | var list1 = new List(2) {1, 2, 3, 4}; 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Tests/Resources/ListInitializerAfter1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Examples.Lists 4 | { 5 | public class ListInitializer 6 | { 7 | public void Method1() 8 | { 9 | var list1 = new List(4) { 1, 2, 3, 4}; 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Tests/Resources/ListInitializerAfter2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Examples.Lists 4 | { 5 | public class ListInitializer 6 | { 7 | public void Method1() 8 | { 9 | var list1 = new List(4) { 1, 2, 3, 4}; 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Tests/Resources/ArrayContainsAfter3.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Collections.Generic; 3 | 4 | class TestClass 5 | { 6 | private readonly HashSet _list2 = new HashSet { 1, 2, 3, 4 }; 7 | 8 | public bool Method() 9 | { 10 | return _list2.Contains(5); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Tests/Resources/ListInitializerBefore1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Examples.Lists 4 | { 5 | public class ListInitializer 6 | { 7 | public void Method1() 8 | { 9 | var list1 = {|CI0006:new List {1, 2, 3, 4}|}; 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Tests/Resources/ListInitializerBefore2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace Examples.Lists 4 | { 5 | public class ListInitializer 6 | { 7 | public void Method1() 8 | { 9 | var list1 = {|CI0006:new List(2) {1, 2, 3, 4}|}; 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /Tests/Resources/ArrayContainsAfter1.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Collections.Generic; 3 | 4 | class TestClass 5 | { 6 | void TestMethod() 7 | { 8 | var numbers = new HashSet(new[] { 1, 2, 3, 4, 5 }); 9 | if (numbers.Contains(3)) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Tests/Resources/ArrayContainsAfter2.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Collections.Generic; 3 | 4 | class TestClass 5 | { 6 | private readonly HashSet _list2 = new HashSet(new int[] { 1, 2, 3, 4 }); 7 | 8 | public bool Method() 9 | { 10 | return _list2.Contains(5); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Tests/Resources/SelectStringToArray.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System.Linq; 4 | 5 | public class LinqMethods 6 | { 7 | public void ToArraySelect() 8 | { 9 | var str = "string"; 10 | 11 | var result = str.ToArray().Select(o => o); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Tests/Resources/ArrayContainsAfter4.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Collections.Generic; 3 | 4 | class TestClass 5 | { 6 | public HashSet List3 { get; } = new HashSet(new[] { 1, 2, 3, 4 }); 7 | 8 | public bool Check(int value) 9 | { 10 | return List3.Contains(value); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Tests/Resources/ListCountAfter.txt: -------------------------------------------------------------------------------- 1 | namespace Examples.Enumerable 2 | { 3 | using System.Linq; 4 | 5 | public class Count 6 | { 7 | public void Method2() 8 | { 9 | var array = new[] { 1, 2, 3 }; 10 | 11 | var result = array.Select(o => o * o).Count(); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Tests/Resources/ArrayToArrayAfter.txt: -------------------------------------------------------------------------------- 1 | namespace Examples.Arrays 2 | { 3 | using System; 4 | using System.Linq; 5 | 6 | public class ArrayToArray 7 | { 8 | public static void Convert() 9 | { 10 | var array = Array.Empty(); 11 | var result = array; 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Tests/Resources/EnumerablePropertyToArray.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | public class C { 5 | public static IEnumerable Property1 6 | { 7 | get 8 | { 9 | var list = new HashSet(); 10 | 11 | return list.ToList(); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Tests/Resources/StringJoinAfter.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | namespace Examples.Strings 4 | { 5 | public class Join 6 | { 7 | public static void JoinArray() 8 | { 9 | var array = new int[10]; 10 | 11 | var result = string.Join("; ", array.Where(o => o != 1)); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Examples/HashSets/DistinctToArray.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.HashSets; 5 | 6 | public class DistinctToArray 7 | { 8 | public void Method1() 9 | { 10 | var numbers = new[] { 1, 2, 3 }; 11 | ICollection result = numbers.Distinct().ToArray(); 12 | } 13 | } -------------------------------------------------------------------------------- /Tests/Resources/ArrayToArray.txt: -------------------------------------------------------------------------------- 1 | namespace Examples.Arrays 2 | { 3 | using System; 4 | using System.Linq; 5 | 6 | public class ArrayToArray 7 | { 8 | public static void Convert() 9 | { 10 | var array = Array.Empty(); 11 | var result = array.ToArray(); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Tests/Resources/StringJoin1.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | namespace Examples.Strings 4 | { 5 | public class Join 6 | { 7 | public static void JoinArray() 8 | { 9 | var array = new int[10]; 10 | 11 | var result = string.Join("; ", array.Where(o => o != 1).ToArray()); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Documentation/CI0006.md: -------------------------------------------------------------------------------- 1 | # CI0006: Collection initializer is used without capacity 2 | Using collection initializer without capacity harms performance and cause additional memory allocation. 3 | 4 | ## Examples 5 | ```csharp 6 | var list = new List {1, 2, 3, 4}; 7 | ``` 8 | ```csharp 9 | var list = new List(2) {"1", "2", "3", "4"}; 10 | ``` -------------------------------------------------------------------------------- /Tests/Resources/ArrayCountAfter.txt: -------------------------------------------------------------------------------- 1 | namespace Examples.Enumerable 2 | { 3 | using System.Linq; 4 | 5 | public class Count 6 | { 7 | public void Method1() 8 | { 9 | var array = new[] { 1, 2, 3 }; 10 | 11 | var result = array.Select(o => o * o).Where(o => o < 3).Count(); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Tests/Resources/ListCountBefore.txt: -------------------------------------------------------------------------------- 1 | namespace Examples.Enumerable 2 | { 3 | using System.Linq; 4 | 5 | public class Count 6 | { 7 | public void Method2() 8 | { 9 | var array = new[] { 1, 2, 3 }; 10 | 11 | var result = {|CI0005:array.Select(o => o * o).ToList().Count|}; 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Examples/Strings/Constructor.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Strings 5 | { 6 | public class Constructor 7 | { 8 | public static void List() 9 | { 10 | var str = "string"; 11 | 12 | var result = new List(str.ToArray()); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ArrayToArrayBefore.txt: -------------------------------------------------------------------------------- 1 | namespace Examples.Arrays 2 | { 3 | using System; 4 | using System.Linq; 5 | 6 | public class ArrayToArray 7 | { 8 | public static void Convert() 9 | { 10 | var array = Array.Empty(); 11 | var result = {|CI0002:array.ToArray()|}; 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Tests/Resources/StringJoinBefore.txt: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | namespace Examples.Strings 4 | { 5 | public class Join 6 | { 7 | public static void JoinArray() 8 | { 9 | var array = new int[10]; 10 | 11 | var result = string.Join("; ", {|CI0003:array.Where(o => o != 1).ToArray()|}); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Tests/Resources/StringListConstructor2.txt: -------------------------------------------------------------------------------- 1 | namespace Examples.Strings 2 | { 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | public class Constructor 7 | { 8 | public static void List() 9 | { 10 | var str = "string"; 11 | 12 | var result = new List(str); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/ArrayTests/AddRangeVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0003; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.ArrayTests; 6 | 7 | public class AddRangeVerifier : CodeFixVerifier 10 | { 11 | } -------------------------------------------------------------------------------- /Tests/Resources/ArrayCountBefore.txt: -------------------------------------------------------------------------------- 1 | namespace Examples.Enumerable 2 | { 3 | using System.Linq; 4 | 5 | public class Count 6 | { 7 | public void Method1() 8 | { 9 | var array = new[] { 1, 2, 3 }; 10 | 11 | var result = {|CI0005:array.Select(o => o * o).Where(o => o < 3).ToArray().Length|}; 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Tests/Resources/EnumerableMethodToArray.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | public class ReturnArray 7 | { 8 | public static IEnumerable Method1() 9 | { 10 | var list = new List(); 11 | 12 | return list.ToArray(); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/StringListConstructorBefore2.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | public class Constructor 7 | { 8 | public static void List() 9 | { 10 | var str = "string"; 11 | 12 | var result = new List({|CI0004:str|}); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/StringListConstructor1.txt: -------------------------------------------------------------------------------- 1 | namespace Examples.Strings 2 | { 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | public class Constructor 7 | { 8 | public static void List() 9 | { 10 | var str = "string"; 11 | 12 | var result = new List(str.ToArray()); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/StringListConstructorAfter.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | public class Constructor 7 | { 8 | public static void List() 9 | { 10 | var str = "string"; 11 | 12 | var result = new List(str.ToCharArray()); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/ArrayTests/ConstructorVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0003; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.ArrayTests; 6 | 7 | public class ConstructorVerifier : CodeFixVerifier 10 | { 11 | } -------------------------------------------------------------------------------- /Tests/Resources/ForeachStringToCharArrayAfter.txt: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace Examples 3 | { 4 | public class Foreach 5 | { 6 | public static void RunForeach() 7 | { 8 | var value = "string"; 9 | 10 | foreach (var c in value) 11 | { 12 | Console.WriteLine(c); 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Tests/Resources/StringListConstructorBefore1.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | public class Constructor 7 | { 8 | public static void List() 9 | { 10 | var str = "string"; 11 | 12 | var result = new List({|CI0004:str.ToArray()|}); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ForeachStringToCharArray.txt: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace Examples 3 | { 4 | public class Foreach 5 | { 6 | public static void RunForeach() 7 | { 8 | var str = "string"; 9 | 10 | foreach (var c in str.ToCharArray()) 11 | { 12 | Console.WriteLine(c); 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Tests/StringTests/ListFromStringVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0004; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.StringTests; 6 | 7 | public class ListFromStringVerifier : CodeFixVerifier 10 | { 11 | } -------------------------------------------------------------------------------- /Tests/Resources/AssignEnumerableAfter2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class AssignEnumerable 7 | { 8 | public void Method2() 9 | { 10 | var enumerable = System.Linq.Enumerable.Empty(); 11 | IEnumerable result = enumerable; 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Tests/ListTests/ListCapacityVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0006; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.ListTests; 6 | 7 | public class ListCapacityVerifier : CodeFixVerifier< 8 | ListInitializerDiagnostic, 9 | SetListCapacityCodeFix, 10 | ListCapacityTests, 11 | DefaultVerifier> 12 | { 13 | } -------------------------------------------------------------------------------- /Tests/Resources/AddRangeAfter.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class AddRange 7 | { 8 | public void Method1() 9 | { 10 | var list = new List(); 11 | IEnumerable array = new int[10]; 12 | 13 | list.AddRange(array); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Tests/Resources/AssignEnumerable1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class AssignEnumerable 7 | { 8 | public void Method2() 9 | { 10 | var enumerable = System.Linq.Enumerable.Empty(); 11 | IEnumerable result = enumerable.ToArray(); 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentBag1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var bag = new ConcurrentBag(new[] { "a", "b", "c" }); 11 | 12 | return bag.Any(); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/AddRange1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class AddRange 7 | { 8 | public void Method1() 9 | { 10 | var list = new List(); 11 | IEnumerable array = new int[10]; 12 | 13 | list.AddRange(array.ToArray()); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentBagAfter1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var bag = new ConcurrentBag(new[] { "a", "b", "c" }); 11 | 12 | return !bag.IsEmpty; 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentBagAfter4.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var bag = new ConcurrentBag(new[] { "a", "b", "c" }); 11 | 12 | return bag.IsEmpty; 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentQueue1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var queue = new ConcurrentQueue(new[] { "a", "b", "c" }); 11 | 12 | return queue.Any(); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentStack1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var stack = new ConcurrentStack(new[] { "a", "b", "c" }); 11 | 12 | return stack.Any(); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ForeachStringToCharArrayBefore.txt: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace Examples 3 | { 4 | public class Foreach 5 | { 6 | public static void RunForeach() 7 | { 8 | var value = "string"; 9 | 10 | foreach (var c in {|CI0001:value.ToCharArray()|}) 11 | { 12 | Console.WriteLine(c); 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Tests/Resources/AssignEnumerableBefore2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class AssignEnumerable 7 | { 8 | public void Method2() 9 | { 10 | var enumerable = System.Linq.Enumerable.Empty(); 11 | IEnumerable result = {|CI0003:enumerable.ToList()|}; 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentBag3.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method2() 9 | { 10 | var bag = new ConcurrentBag(new[] { "a", "b", "c" }); 11 | 12 | return bag.Any(o => o == "d"); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentQueueAfter1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var queue = new ConcurrentQueue(new[] { "a", "b", "c" }); 11 | 12 | return !queue.IsEmpty; 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentQueueAfter4.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var queue = new ConcurrentQueue(new[] { "a", "b", "c" }); 11 | 12 | return queue.IsEmpty; 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentStackAfter1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var stack = new ConcurrentStack(new[] { "a", "b", "c" }); 11 | 12 | return !stack.IsEmpty; 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentStackAfter4.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var stack = new ConcurrentStack(new[] { "a", "b", "c" }); 11 | 12 | return stack.IsEmpty; 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/AddRangeBefore.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class AddRange 7 | { 8 | public void Method1() 9 | { 10 | var list = new List(); 11 | IEnumerable array = new int[10]; 12 | 13 | list.AddRange({|CI0003:array.ToArray()|}); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentBagBefore1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var bag = new ConcurrentBag(new[] { "a", "b", "c" }); 11 | 12 | return {|CI0007:bag.Any|}(); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentBagBefore4.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var bag = new ConcurrentBag(new[] { "a", "b", "c" }); 11 | 12 | return !{|CI0007:bag.Any|}(); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentQueue3.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method2() 9 | { 10 | var queue = new ConcurrentQueue(new[] { "a", "b", "c" }); 11 | 12 | return queue.Any(o => o == "d"); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentStack3.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method2() 9 | { 10 | var stack = new ConcurrentStack(new[] { "a", "b", "c" }); 11 | 12 | return stack.Any(o => o == "d"); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ForeachStringToArrayAfter.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System; 4 | using System.Linq; 5 | 6 | public class ForeachToArray 7 | { 8 | public static void RunForeach() 9 | { 10 | var str = "string"; 11 | 12 | foreach (var c in str) 13 | { 14 | Console.WriteLine(c); 15 | } 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/ForeachStringToListAfter.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System; 4 | using System.Linq; 5 | 6 | public class ForeachToArray 7 | { 8 | public static void RunForeach() 9 | { 10 | var str = "string"; 11 | 12 | foreach (var c in str) 13 | { 14 | Console.WriteLine(c); 15 | } 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentQueueBefore1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var queue = new ConcurrentQueue(new[] { "a", "b", "c" }); 11 | 12 | return {|CI0007:queue.Any|}(); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentQueueBefore4.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var queue = new ConcurrentQueue(new[] { "a", "b", "c" }); 11 | 12 | return !{|CI0007:queue.Any|}(); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentStackBefore1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var stack = new ConcurrentStack(new[] { "a", "b", "c" }); 11 | 12 | return {|CI0007:stack.Any|}(); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentStackBefore4.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var stack = new ConcurrentStack(new[] { "a", "b", "c" }); 11 | 12 | return !{|CI0007:stack.Any|}(); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Tests/Resources/ForeachStringToArray.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System; 4 | using System.Linq; 5 | 6 | public class ForeachToArray 7 | { 8 | public static void RunForeach() 9 | { 10 | var str = "string"; 11 | 12 | foreach (var c in str.ToArray()) 13 | { 14 | Console.WriteLine(c); 15 | } 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/ArrayTests/ObjectInitializerVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0003; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.ArrayTests; 6 | 7 | public sealed class ObjectInitializerVerifier: CodeFixVerifier 10 | { 11 | 12 | } -------------------------------------------------------------------------------- /Tests/Resources/GetArrayToArrayAfter.txt: -------------------------------------------------------------------------------- 1 | namespace Examples.Arrays 2 | { 3 | using System; 4 | using System.Linq; 5 | 6 | public class ArrayToArray 7 | { 8 | public static void ConvertFromMethod() 9 | { 10 | var result = GetArray(); 11 | } 12 | 13 | private static int[] GetArray() 14 | { 15 | return Array.Empty(); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/EnumerableTests/AssignEnumerableVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0003; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.EnumerableTests; 6 | 7 | public class AssignEnumerableVerifier : CodeFixVerifier< 8 | AssignEnumerableDiagnostic, 9 | RemoveRedundantMethodCallCodeFix, 10 | AssignEnumerableTests, 11 | DefaultVerifier> 12 | { 13 | } -------------------------------------------------------------------------------- /Documentation/CI0002.md: -------------------------------------------------------------------------------- 1 | # CI0002: Redundant array conversion 2 | Redundant ToArray method call on array. 3 | 4 | ## Examples 5 | ```csharp 6 | var array = Array.Empty(); 7 | var result = array.ToArray(); 8 | ``` 9 | 10 | ```csharp 11 | public static void ConvertFromMethod() 12 | { 13 | var result = GetArray().ToArray(); 14 | } 15 | 16 | private static int[] GetArray() 17 | { 18 | return Array.Empty(); 19 | } 20 | ``` -------------------------------------------------------------------------------- /Tests/ArrayLengthTests/RedundantToArrayLengthVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0005; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.ArrayLengthTests; 6 | 7 | internal sealed class RedundantToArrayLengthVerifier : CodeFixVerifier 11 | { 12 | } -------------------------------------------------------------------------------- /Tests/Resources/ForeachStringToListBefore.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System; 4 | using System.Linq; 5 | 6 | public class ForeachToArray 7 | { 8 | public static void RunForeach() 9 | { 10 | var str = "string"; 11 | 12 | foreach (var c in {|CI0001:str.ToList()|}) 13 | { 14 | Console.WriteLine(c); 15 | } 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/GetArrayToArray.txt: -------------------------------------------------------------------------------- 1 | namespace Examples.Arrays 2 | { 3 | using System; 4 | using System.Linq; 5 | 6 | public class ArrayToArray 7 | { 8 | public static void ConvertFromMethod() 9 | { 10 | var result = GetArray().ToArray(); 11 | } 12 | 13 | private static int[] GetArray() 14 | { 15 | return Array.Empty();; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/GetStringSelectToArray.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | public class Constructor 7 | { 8 | public static void List() 9 | { 10 | var result = GetString().ToArray().Select(o => o); 11 | } 12 | private static string GetString() 13 | { 14 | return "str"; 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Tests/Resources/GetStringToCharArraySelectAfter.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | public class Constructor 7 | { 8 | public static void List() 9 | { 10 | var result = GetString().Select(o => o); 11 | } 12 | private static string GetString() 13 | { 14 | return "str"; 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Tests/Resources/ForeachStringToArrayBefore.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System; 4 | using System.Linq; 5 | 6 | public class ForeachToArray 7 | { 8 | public static void RunForeach() 9 | { 10 | var str = "string"; 11 | 12 | foreach (var c in {|CI0001:str.ToArray()|}) 13 | { 14 | Console.WriteLine(c); 15 | } 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/GetSetToArray.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | public class SetToArray 7 | { 8 | public static IEnumerable Method() 9 | { 10 | return GetSet().ToArray(); 11 | } 12 | 13 | public static HashSet GetSet() 14 | { 15 | return new HashSet(); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Benchmarks/Benchmarks.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0;net8.0;net48 6 | enable 7 | 8 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Tests/Resources/AssignEnumerableAfter1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class AssignEnumerable 7 | { 8 | public void Method1() 9 | { 10 | IEnumerable result = GetArray(); 11 | } 12 | 13 | private static IEnumerable GetArray() 14 | { 15 | return new int[10]; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/AsyncEnumerableMethodToArray2.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System.Collections.Generic; 4 | using System.Threading.Tasks; 5 | 6 | public class ReturnArray 7 | { 8 | public static async ValueTask> Method1() 9 | { 10 | var list = new List { 1 }; 11 | await Task.CompletedTask; 12 | 13 | return list.ToArray(); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Tests/Resources/GetArrayToArrayBefore.txt: -------------------------------------------------------------------------------- 1 | namespace Examples.Arrays 2 | { 3 | using System; 4 | using System.Linq; 5 | 6 | public class ArrayToArray 7 | { 8 | public static void ConvertFromMethod() 9 | { 10 | var result = {|CI0002:GetArray().ToArray()|}; 11 | } 12 | 13 | private static int[] GetArray() 14 | { 15 | return Array.Empty(); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/ArrayContainsToHashSetTests/ArrayContainsVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0008; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.ArrayContainsToHashSetTests; 6 | 7 | public class ArrayContainsVerifier : CodeFixVerifier< 8 | ArrayContainsToHashSetDiagnostic, 9 | ArrayContainsToHashSetCodeFix, 10 | ArrayContainsToHashSetTests, 11 | DefaultVerifier> 12 | { 13 | } -------------------------------------------------------------------------------- /Tests/ConcurrentBagIsEmptyTests/ConcurrentBagIsEmptyVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0007; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.ConcurrentBagIsEmptyTests; 6 | 7 | public class ConcurrentBagIsEmptyVerifier : CodeFixVerifier< 8 | ConcurrentCollectionIsEmptyDiagnostic, 9 | ReplaceAnyWithIsEmptyCodeFix, 10 | IsEmptyTests, 11 | DefaultVerifier> 12 | { 13 | } -------------------------------------------------------------------------------- /Tests/StringTests/StringJoinToArrayConversionVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0003; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.StringTests; 6 | 7 | internal sealed class StringJoinToArrayConversionVerifier : CodeFixVerifier 11 | { 12 | } -------------------------------------------------------------------------------- /Tests/ArrayTests/RedundantArrayToArrayConversionVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0002; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.ArrayTests; 6 | 7 | internal sealed class RedundantArrayToArrayConversionVerifier : CodeFixVerifier< 8 | ArrayToArrayDiagnostic, RemoveRedundantMethodCallCodeFix, 9 | RedundantArrayToArrayConversionTests, 10 | DefaultVerifier> 11 | { 12 | } -------------------------------------------------------------------------------- /Tests/Resources/AssignEnumerable2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class AssignEnumerable 7 | { 8 | public void Method1() 9 | { 10 | IEnumerable result = GetArray().ToArray(); 11 | } 12 | 13 | private static IEnumerable GetArray() 14 | { 15 | return new int[10]; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentDictionary1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method() 9 | { 10 | var dict = new ConcurrentDictionary 11 | { 12 | [0] = "str" 13 | }; 14 | 15 | return dict.Any(); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/GetStringToCharArraySelectBefore.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | public class Constructor 7 | { 8 | public static void List() 9 | { 10 | var result = {|CI0001:GetString().ToCharArray()|}.Select(o => o); 11 | } 12 | private static string GetString() 13 | { 14 | return "str"; 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /Tests/ConcurrentQueueIsEmptyTests/ConcurrentQueueIsEmptyVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0007; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.ConcurrentQueueIsEmptyTests; 6 | 7 | public class ConcurrentQueueIsEmptyVerifier : CodeFixVerifier< 8 | ConcurrentCollectionIsEmptyDiagnostic, 9 | ReplaceAnyWithIsEmptyCodeFix, 10 | IsEmptyTests, 11 | DefaultVerifier> 12 | { 13 | } -------------------------------------------------------------------------------- /Tests/ConcurrentStackIsEmptyTests/ConcurrentQueueIsEmptyVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0007; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.ConcurrentStackIsEmptyTests; 6 | 7 | public class ConcurrentStackIsEmptyVerifier : CodeFixVerifier< 8 | ConcurrentCollectionIsEmptyDiagnostic, 9 | ReplaceAnyWithIsEmptyCodeFix, 10 | IsEmptyTests, 11 | DefaultVerifier> 12 | { 13 | } -------------------------------------------------------------------------------- /Tests/StringTests/RedundantStringToArrayConversionVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0001; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.StringTests; 6 | 7 | internal sealed class RedundantStringToArrayConversionVerifier : CodeFixVerifier< 8 | StringToArrayDiagnostic, RemoveRedundantMethodCallCodeFix, 9 | RedundantStringToArrayConversionTests, 10 | DefaultVerifier> 11 | { 12 | } -------------------------------------------------------------------------------- /Tests/Resources/AssignEnumerableBefore1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class AssignEnumerable 7 | { 8 | public void Method1() 9 | { 10 | IEnumerable result = {|CI0003:GetArray().ToArray()|}; 11 | } 12 | 13 | private static IEnumerable GetArray() 14 | { 15 | return new int[10]; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentDictionaryAfter1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method() 9 | { 10 | var dict = new ConcurrentDictionary 11 | { 12 | [0] = "str" 13 | }; 14 | 15 | return !dict.IsEmpty; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentDictionaryAfter4.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method() 9 | { 10 | var dict = new ConcurrentDictionary 11 | { 12 | [0] = "str" 13 | }; 14 | 15 | return dict.IsEmpty; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/AddRange2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class AddRange 7 | { 8 | public void Method2() 9 | { 10 | var list = new List(); 11 | 12 | list.AddRange(GetArray().ToArray()); 13 | } 14 | 15 | private static IEnumerable GetArray() 16 | { 17 | return new int[10]; 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentDictionaryBefore1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method() 9 | { 10 | var dict = new ConcurrentDictionary 11 | { 12 | [0] = "str" 13 | }; 14 | 15 | return {|CI0007:dict.Any|}(); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentDictionaryBefore4.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method() 9 | { 10 | var dict = new ConcurrentDictionary 11 | { 12 | [0] = "str" 13 | }; 14 | 15 | return !{|CI0007:dict.Any|}(); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/ConcurrentDictionaryIsEmptyTests/ConcurrentDictionaryIsEmptyVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0007; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.ConcurrentDictionaryIsEmptyTests; 6 | 7 | public class ConcurrentDictionaryIsEmptyVerifier : CodeFixVerifier< 8 | ConcurrentCollectionIsEmptyDiagnostic, 9 | ReplaceAnyWithIsEmptyCodeFix, 10 | IsEmptyTests, 11 | DefaultVerifier> 12 | { 13 | } -------------------------------------------------------------------------------- /Tests/Resources/AsyncEnumerableMethodToArray.txt: -------------------------------------------------------------------------------- 1 | namespace Examples 2 | { 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | public class ReturnArray 8 | { 9 | public static async Task> Method1() 10 | { 11 | var list = new List(); 12 | 13 | await Task.CompletedTask; 14 | 15 | return list.ToArray(); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentBag2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method3() 9 | { 10 | return GetBag().Any(); 11 | } 12 | 13 | private static ConcurrentBag GetBag() 14 | { 15 | return new ConcurrentBag(new[] { "a", "b", "c" }); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentDictionary2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method() 9 | { 10 | var dict = new ConcurrentDictionary 11 | { 12 | [0] = "str" 13 | }; 14 | 15 | return dict.Any(o => o.Value == "123"); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentBagAfter2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method3() 9 | { 10 | return !GetBag().IsEmpty; 11 | } 12 | 13 | private static ConcurrentBag GetBag() 14 | { 15 | return new ConcurrentBag(new[] { "a", "b", "c" }); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentQueue2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method3() 9 | { 10 | return GetQueue().Any(); 11 | } 12 | 13 | private static ConcurrentQueue GetQueue() 14 | { 15 | return new ConcurrentQueue(new[] { "a", "b", "c" }); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentStack2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method3() 9 | { 10 | return GetStack().Any(); 11 | } 12 | 13 | private static ConcurrentStack GetStack() 14 | { 15 | return new ConcurrentStack(new[] { "a", "b", "c" }); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/EnumerableTests/RedundantEnumerableToArrayConversionVerifier.cs: -------------------------------------------------------------------------------- 1 | using Collections.Analyzer.CodeFixes; 2 | using Collections.Analyzer.Diagnostics.CI0003; 3 | using Microsoft.CodeAnalysis.Testing; 4 | 5 | namespace Tests.EnumerableTests; 6 | 7 | internal sealed class RedundantEnumerableToArrayConversionVerifier : CodeFixVerifier< 8 | EnumerableToArrayOnReturnDiagnostic, RemoveRedundantMethodCallCodeFix, 9 | RedundantEnumerableToArrayConversionTests, 10 | DefaultVerifier> 11 | { 12 | } -------------------------------------------------------------------------------- /Tests/ResourceReader.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using System.Reflection; 3 | 4 | namespace Tests; 5 | 6 | internal static class ResourceReader 7 | { 8 | public static string ReadFromFile(string resourceName) 9 | { 10 | var assembly = Assembly.GetExecutingAssembly(); 11 | 12 | using var stream = assembly.GetManifestResourceStream("Tests.Resources." + resourceName); 13 | using var reader = new StreamReader(stream); 14 | return reader.ReadToEnd(); 15 | } 16 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentBagBefore2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method3() 9 | { 10 | return {|CI0007:GetBag().Any|}(); 11 | } 12 | 13 | private static ConcurrentBag GetBag() 14 | { 15 | return new ConcurrentBag(new[] { "a", "b", "c" }); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentQueueAfter2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method3() 9 | { 10 | return !GetQueue().IsEmpty; 11 | } 12 | 13 | private static ConcurrentQueue GetQueue() 14 | { 15 | return new ConcurrentQueue(new[] { "a", "b", "c" }); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentStackAfter2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method3() 9 | { 10 | return !GetStack().IsEmpty; 11 | } 12 | 13 | private static ConcurrentStack GetStack() 14 | { 15 | return new ConcurrentStack(new[] { "a", "b", "c" }); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Documentation/CI0004.md: -------------------------------------------------------------------------------- 1 | # CI0004: Not optimal `List` constructor usage 2 | String parameter for `List` constructor is better to use with `ToCharArray` call. [More information](https://blog.rogatnev.net/posts/2021/09/Harmful-collection-transformations-part-1-strings.html). 3 | 4 | ## Examples 5 | ```csharp 6 | var result = new List(str.ToArray()); 7 | ``` 8 | 9 | ```csharp 10 | var result = new List(str.ToList()); 11 | ``` 12 | 13 | ```csharp 14 | var result = new List(str); 15 | ``` -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentQueueBefore2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method3() 9 | { 10 | return {|CI0007:GetQueue().Any|}(); 11 | } 12 | 13 | private static ConcurrentQueue GetQueue() 14 | { 15 | return new ConcurrentQueue(new[] { "a", "b", "c" }); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentStackBefore2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method3() 9 | { 10 | return {|CI0007:GetStack().Any|}(); 11 | } 12 | 13 | private static ConcurrentStack GetStack() 14 | { 15 | return new ConcurrentStack(new[] { "a", "b", "c" }); 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /Documentation/CI0007.md: -------------------------------------------------------------------------------- 1 | # CI0007: Method Any() is used on concurrent collection 2 | Method `Any()` is much slower on concurrent collections than `IsEmpty` property. 3 | Using collection initializer without capacity harms performance and cause additional memory allocation. 4 | 5 | ## Examples 6 | ```csharp 7 | var bag = new ConcurrentBag(new[] { "a", "b", "c" }); 8 | 9 | var hasAny = bag.Any(); 10 | ``` 11 | ```csharp 12 | var bag = new ConcurrentBag(new[] { "a", "b", "c" }); 13 | 14 | var hasAny = !bag.IsEmpty; 15 | ``` -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentBagAfter3.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class C 7 | { 8 | public void Method6() 9 | { 10 | var bag = new ConcurrentBag(new[] { "a", "b", "c" }); 11 | 12 | WithEmpty(!bag.IsEmpty); 13 | } 14 | 15 | private void WithEmpty(bool b) 16 | { 17 | throw new System.NotImplementedException(); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentQueueAfter3.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class C 7 | { 8 | public void Method6() 9 | { 10 | var bag = new ConcurrentQueue(new[] { "a", "b", "c" }); 11 | 12 | WithEmpty(!bag.IsEmpty); 13 | } 14 | 15 | private void WithEmpty(bool b) 16 | { 17 | throw new System.NotImplementedException(); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentStackAfter3.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class C 7 | { 8 | public void Method6() 9 | { 10 | var bag = new ConcurrentStack(new[] { "a", "b", "c" }); 11 | 12 | WithEmpty(!bag.IsEmpty); 13 | } 14 | 15 | private void WithEmpty(bool b) 16 | { 17 | throw new System.NotImplementedException(); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Documentation/CI0005.md: -------------------------------------------------------------------------------- 1 | # CI0005: Not optimal count of collection items 2 | Redundant ToArray method call to get Length property or ToList and Count. 3 | 4 | ## Examples 5 | ```csharp 6 | var array = new[] { 1, 2, 3 }; 7 | var result = array.Select(o => o * o).Where(o => o < 3).ToArray().Length; 8 | ``` 9 | 10 | ```csharp 11 | var array = new[] { 1, 2, 3 }; 12 | var result = array.Select(o => o * o).ToList().Count; 13 | ``` 14 | 15 | ```csharp 16 | var array = new HashSet(new[] { 1, 2, 3 }); 17 | var result = array.ToArray().Length; 18 | ``` -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentBagBefore3.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class C 7 | { 8 | public void Method6() 9 | { 10 | var bag = new ConcurrentBag(new[] { "a", "b", "c" }); 11 | 12 | WithEmpty({|CI0007:bag.Any|}()); 13 | } 14 | 15 | private void WithEmpty(bool b) 16 | { 17 | throw new System.NotImplementedException(); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentQueueBefore3.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class C 7 | { 8 | public void Method6() 9 | { 10 | var bag = new ConcurrentQueue(new[] { "a", "b", "c" }); 11 | 12 | WithEmpty({|CI0007:bag.Any|}()); 13 | } 14 | 15 | private void WithEmpty(bool b) 16 | { 17 | throw new System.NotImplementedException(); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentStackBefore3.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class C 7 | { 8 | public void Method6() 9 | { 10 | var bag = new ConcurrentStack(new[] { "a", "b", "c" }); 11 | 12 | WithEmpty({|CI0007:bag.Any|}()); 13 | } 14 | 15 | private void WithEmpty(bool b) 16 | { 17 | throw new System.NotImplementedException(); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentDictionary3.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method3() 9 | { 10 | return GetDict().Any(); 11 | } 12 | 13 | private static ConcurrentDictionary GetDict() 14 | { 15 | return new ConcurrentDictionary 16 | { 17 | [0] = "str" 18 | }; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentDictionaryAfter2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method3() 9 | { 10 | return !GetDict().IsEmpty; 11 | } 12 | 13 | private static ConcurrentDictionary GetDict() 14 | { 15 | return new ConcurrentDictionary 16 | { 17 | [0] = "str" 18 | }; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentDictionaryBefore2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class DictionaryIsEmpty 7 | { 8 | public bool Method3() 9 | { 10 | return {|CI0007:GetDict().Any|}(); 11 | } 12 | 13 | private static ConcurrentDictionary GetDict() 14 | { 15 | return new ConcurrentDictionary 16 | { 17 | [0] = "str" 18 | }; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /Examples/Examples.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | 10 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Examples/Strings/Join.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | namespace Examples.Strings 4 | { 5 | public class Join 6 | { 7 | public static void JoinArray() 8 | { 9 | var array = new int[10]; 10 | 11 | var result = string.Join("; ", array.Where(o => o != 1).ToArray()); 12 | } 13 | 14 | public static void MethodJoinArray() 15 | { 16 | var result = string.Join("; ", GetArray().Where(o => o != 1).ToList()); 17 | } 18 | 19 | private static int[] GetArray() 20 | { 21 | return new int[10]; 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentDictionaryAfter3.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class C 7 | { 8 | public void Method6() 9 | { 10 | var dict = new ConcurrentDictionary 11 | { 12 | [0] = "str" 13 | }; 14 | 15 | WithEmpty(!dict.IsEmpty); 16 | } 17 | 18 | private void WithEmpty(bool b) 19 | { 20 | throw new System.NotImplementedException(); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Tests/Resources/Constructor4.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class Constructor 7 | { 8 | public void CallConstructor() 9 | { 10 | ICollection list = new int[10]; 11 | 12 | var obj = new MyClass(list.ToArray()); 13 | } 14 | 15 | private class MyClass 16 | { 17 | private readonly ICollection source; 18 | 19 | public MyClass(ICollection source) 20 | { 21 | source = source; 22 | } 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Tests/Resources/ConcurrentDictionaryBefore3.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections 5 | { 6 | public class C 7 | { 8 | public void Method6() 9 | { 10 | var dict = new ConcurrentDictionary 11 | { 12 | [0] = "str" 13 | }; 14 | 15 | WithEmpty({|CI0007:dict.Any|}()); 16 | } 17 | 18 | private void WithEmpty(bool b) 19 | { 20 | throw new System.NotImplementedException(); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Examples/Enumerable/AssignEnumerable.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class AssignEnumerable 7 | { 8 | public void Method1() 9 | { 10 | IEnumerable result = GetArray().ToArray(); 11 | } 12 | 13 | public void Method2() 14 | { 15 | var enumerable = System.Linq.Enumerable.Empty(); 16 | IEnumerable result = enumerable.ToList(); 17 | } 18 | 19 | private static IEnumerable GetArray() 20 | { 21 | return new int[10]; 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Tests/Resources/Constructor1.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class Constructor 7 | { 8 | public void CallConstructor() 9 | { 10 | var list = System.Linq.Enumerable.Empty(); 11 | 12 | var obj = new MyClass(list.ToArray()); 13 | } 14 | 15 | private class MyClass 16 | { 17 | private readonly IEnumerable source; 18 | 19 | public MyClass(IEnumerable source) 20 | { 21 | source = source; 22 | } 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Tests/Resources/ObjectInitializerAfter.txt: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | public class C 4 | { 5 | private static void Initialize() 6 | { 7 | var value1 = new MyClass 8 | { 9 | ArrayProperty1 = Array.Empty(), 10 | ArrayProperty2 = Array.Empty() 11 | }; 12 | 13 | var value2 = new MyClass 14 | { 15 | ArrayProperty1 = value1.ArrayProperty1, 16 | ArrayProperty2 = value1.ArrayProperty2 17 | }; 18 | } 19 | 20 | private class MyClass 21 | { 22 | public int[] ArrayProperty1 { get; set; } 23 | public string[] ArrayProperty2 { get; set; } 24 | } 25 | } -------------------------------------------------------------------------------- /Examples/Enumerable/AddRange.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class AddRange 7 | { 8 | public void Method1() 9 | { 10 | var list = new List(); 11 | IEnumerable array = new int[10]; 12 | 13 | list.AddRange(array.ToArray()); 14 | } 15 | 16 | public void Method2() 17 | { 18 | var list = new List(); 19 | 20 | list.AddRange(GetArray().ToArray()); 21 | } 22 | 23 | private static IEnumerable GetArray() 24 | { 25 | return new int[10]; 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /Tests/Resources/ObjectInitializer.txt: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | public class C 4 | { 5 | private static void Initialize() 6 | { 7 | var value1 = new MyClass 8 | { 9 | ArrayProperty1 = Array.Empty(), 10 | ArrayProperty2 = Array.Empty() 11 | }; 12 | 13 | var value2 = new MyClass 14 | { 15 | ArrayProperty1 = value1.ArrayProperty1.ToArray(), 16 | ArrayProperty2 = value1.ArrayProperty2.ToArray() 17 | }; 18 | } 19 | 20 | private class MyClass 21 | { 22 | public int[] ArrayProperty1 { get; set; } 23 | public string[] ArrayProperty2 { get; set; } 24 | } 25 | } -------------------------------------------------------------------------------- /Tests/Resources/ObjectInitializerBefore.txt: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | public class C 4 | { 5 | private static void Initialize() 6 | { 7 | var value1 = new MyClass 8 | { 9 | ArrayProperty1 = Array.Empty(), 10 | ArrayProperty2 = Array.Empty() 11 | }; 12 | 13 | var value2 = new MyClass 14 | { 15 | ArrayProperty1 = {|CI0003:value1.ArrayProperty1.ToArray()|}, 16 | ArrayProperty2 = value1.ArrayProperty2 17 | }; 18 | } 19 | 20 | private class MyClass 21 | { 22 | public int[] ArrayProperty1 { get; set; } 23 | public string[] ArrayProperty2 { get; set; } 24 | } 25 | } -------------------------------------------------------------------------------- /Examples/ConcurrentCollections/ConcurrentQueueIsEmpty.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections; 5 | 6 | public class ConcurrentQueueIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var queue = new ConcurrentQueue(new[] { "a", "b", "c" }); 11 | 12 | return queue.Any(); 13 | } 14 | 15 | public bool Method2() 16 | { 17 | var queue = new ConcurrentQueue(new[] { "a", "b", "c" }); 18 | 19 | return queue.Any(o => o == "d"); 20 | } 21 | 22 | public bool Method3() 23 | { 24 | return GetQueue().Any(); 25 | } 26 | 27 | private static ConcurrentQueue GetQueue() 28 | { 29 | return new ConcurrentQueue(new[] { "a", "b", "c" }); 30 | } 31 | } -------------------------------------------------------------------------------- /Examples/ConcurrentCollections/ConcurrentStackIsEmpty.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections; 5 | 6 | public class ConcurrentStackIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var stack = new ConcurrentStack(new[] { "a", "b", "c" }); 11 | 12 | return stack.Any(); 13 | } 14 | 15 | public bool Method2() 16 | { 17 | var stack = new ConcurrentStack(new[] { "a", "b", "c" }); 18 | 19 | return stack.Any(o => o == "d"); 20 | } 21 | 22 | public bool Method3() 23 | { 24 | return GetStack().Any(); 25 | } 26 | 27 | private static ConcurrentStack GetStack() 28 | { 29 | return new ConcurrentStack(new[] { "a", "b", "c" }); 30 | } 31 | } -------------------------------------------------------------------------------- /Benchmarks/ArrayToArrayBenchmark.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using BenchmarkDotNet.Attributes; 3 | using BenchmarkDotNet.Jobs; 4 | 5 | namespace Benchmarks 6 | { 7 | [ShortRunJob(RuntimeMoniker.Net48)] 8 | [ShortRunJob(RuntimeMoniker.Net60)] 9 | [MemoryDiagnoser] 10 | public class ArrayToArrayBenchmark 11 | { 12 | [Params(1000, 1000000)] 13 | public int N { get; set; } 14 | 15 | private int[] array; 16 | 17 | [GlobalSetup] 18 | public void SetUp() 19 | { 20 | array = new int[N]; 21 | } 22 | 23 | [Benchmark(Baseline = true)] 24 | public int SumArray() 25 | { 26 | return array.Sum(); 27 | } 28 | 29 | [Benchmark] 30 | public int SumArrayCopy() 31 | { 32 | return array.ToArray().Sum(); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Tests/ArrayLengthTests/RedundantToArrayLengthTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0005; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.ArrayLengthTests; 9 | 10 | public class RedundantToArrayLengthTests : CSharpCodeFixTest 12 | { 13 | [Test] 14 | [TestCase("ArrayCountBefore.txt", "ArrayCountAfter.txt")] 15 | [TestCase("ListCountBefore.txt", "ListCountAfter.txt")] 16 | public Task CodeFixesTest(string before, string after) 17 | { 18 | var code = ResourceReader.ReadFromFile(before); 19 | var fixedCode = ResourceReader.ReadFromFile(after); 20 | 21 | return RedundantToArrayLengthVerifier.VerifyCodeFixAsync(code, fixedCode); 22 | } 23 | } -------------------------------------------------------------------------------- /Examples/Arrays/ArrayContains.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | namespace Examples.Arrays 4 | { 5 | public class ArrayContains 6 | { 7 | public int[] List3 { get; } = new[] { 1, 2, 3, 4 }; 8 | 9 | private readonly int[] _list2 = { 1, 2, 3, 4 }; 10 | 11 | public bool Method1() 12 | { 13 | var list1 = new[] { 1, 2, 3, 4 }; 14 | 15 | return list1.Contains(5); 16 | } 17 | 18 | public bool Method2() 19 | { 20 | return _list2.Contains(5); 21 | } 22 | 23 | public bool Method3() 24 | { 25 | return List3.Contains(5); 26 | } 27 | 28 | public bool Method4() 29 | { 30 | var list = new int[] { 1, 2, 3, 4 }; 31 | 32 | if (list.Contains(2)) 33 | { 34 | return true; 35 | } 36 | 37 | return false; 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /Documentation/CI0008.md: -------------------------------------------------------------------------------- 1 | # CI0008: Consider using HashSet instead of array for Contains operations 2 | An array is used with the `Contains()` method for lookup operations. 3 | 4 | ## Examples 5 | ```csharp 6 | public class ArrayContains 7 | { 8 | public int[] List3 { get; } = new[] { 1, 2, 3, 4 }; 9 | 10 | private readonly int[] _list2 = { 1, 2, 3, 4 }; 11 | 12 | public bool Method1() 13 | { 14 | var list1 = new[] { 1, 2, 3, 4 }; 15 | 16 | return list1.Contains(5); 17 | } 18 | 19 | public bool Method2() 20 | { 21 | return _list2.Contains(5); 22 | } 23 | 24 | public bool Method3() 25 | { 26 | return List3.Contains(5); 27 | } 28 | 29 | public bool Method4() 30 | { 31 | var list = new int[] { 1, 2, 3, 4 }; 32 | 33 | if (list.Contains(2)) 34 | { 35 | return true; 36 | } 37 | 38 | return false; 39 | } 40 | } 41 | ``` -------------------------------------------------------------------------------- /Examples/ConcurrentCollections/ConcurrentDictionaryIsEmpty.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections; 5 | 6 | public class ConcurrentDictionaryIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var dict = new ConcurrentDictionary 11 | { 12 | [0] = "str" 13 | }; 14 | 15 | return dict.Any(); 16 | } 17 | 18 | public bool Method2() 19 | { 20 | var dict = new ConcurrentDictionary 21 | { 22 | [0] = "str" 23 | }; 24 | 25 | return dict.Any(o => o.Value == "str"); 26 | } 27 | 28 | public bool Method3() 29 | { 30 | return GetDict().Any(); 31 | } 32 | 33 | private static ConcurrentDictionary GetDict() 34 | { 35 | return new ConcurrentDictionary 36 | { 37 | [0] = "str" 38 | }; 39 | } 40 | } -------------------------------------------------------------------------------- /Examples/Strings/Foreach.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | namespace Examples.Strings 5 | { 6 | public class Foreach 7 | { 8 | public static void ForeachToArray() 9 | { 10 | var str = "string"; 11 | 12 | foreach (var c in str.ToArray()) Console.WriteLine(c); 13 | } 14 | 15 | public static void ForeachToCharArray() 16 | { 17 | var str = "string"; 18 | 19 | foreach (var c in str.ToCharArray()) Console.WriteLine(c); 20 | } 21 | 22 | public static void ForeachToList() 23 | { 24 | var str = "string"; 25 | 26 | foreach (var c in str.ToList()) Console.WriteLine(c); 27 | } 28 | 29 | public static void ForeachToArrayGetString() 30 | { 31 | foreach (var c in GetString().ToArray()) Console.WriteLine(c); 32 | } 33 | 34 | private static string GetString() 35 | { 36 | return "str"; 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish to NuGet 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | 7 | jobs: 8 | build-and-publish: 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | - name: Checkout code 13 | uses: actions/checkout@v4 14 | 15 | - name: Setup .NET SDK 16 | uses: actions/setup-dotnet@v3 17 | with: 18 | dotnet-version: | 19 | 8.x 20 | 7.x 21 | 6.x 22 | 23 | - name: Restore dependencies 24 | run: dotnet restore 25 | 26 | - name: Build 27 | run: dotnet build --configuration Release --no-restore 28 | 29 | - name: Test 30 | run: dotnet test --configuration Release --no-build --verbosity normal 31 | 32 | - name: Pack 33 | run: dotnet pack Collections.Analyzer/Collections.Analyzer.csproj --configuration Release --no-build --output nupkgs 34 | 35 | - name: Push to NuGet 36 | run: dotnet nuget push nupkgs/*.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json -------------------------------------------------------------------------------- /Benchmarks/AddRangeBenchmark.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using BenchmarkDotNet.Attributes; 4 | using BenchmarkDotNet.Jobs; 5 | 6 | namespace Benchmarks 7 | { 8 | [ShortRunJob(RuntimeMoniker.Net48)] 9 | [ShortRunJob(RuntimeMoniker.Net60)] 10 | [MemoryDiagnoser] 11 | public class AddRangeBenchmark 12 | { 13 | [Params(1000, 1000000)] 14 | public int N { get; set; } 15 | 16 | private int[] array; 17 | 18 | [GlobalSetup] 19 | public void SetUp() 20 | { 21 | array = new int[N]; 22 | } 23 | 24 | [Benchmark(Baseline = true)] 25 | public List AddRangeArray() 26 | { 27 | var list = new List(); 28 | list.AddRange(array); 29 | return list; 30 | } 31 | 32 | [Benchmark] 33 | public List AddRangeArrayCopy() 34 | { 35 | var list = new List(); 36 | list.AddRange(array.ToArray()); 37 | return list; 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /Examples/Enumerable/Count.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class Count 7 | { 8 | public void Method1() 9 | { 10 | var array = new[] {1, 2, 3}; 11 | var result = array.Select(o => o * o).Where(o => o < 3).ToArray().Length; 12 | } 13 | 14 | public void Method2() 15 | { 16 | var array = new[] {1, 2, 3}; 17 | var result = array.Select(o => o * o).ToList().Count; 18 | } 19 | 20 | public void Method3() 21 | { 22 | var array = new[] {1, 2, 3}; 23 | 24 | var result = array.ToList().Count; 25 | } 26 | 27 | public void Method4() 28 | { 29 | var array = new[] {1, 2, 3}; 30 | 31 | var result = array.ToArray().Length; 32 | } 33 | 34 | public void Method5() 35 | { 36 | var array = new HashSet(new[] {1, 2, 3}); 37 | var result = array.ToArray().Length; 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /Examples/Strings/LinqMethods.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | namespace Examples.Strings 4 | { 5 | public class LinqMethods 6 | { 7 | public void ToCharArraySelect() 8 | { 9 | var str = "string"; 10 | 11 | var result = str.ToCharArray().Select(o => o); 12 | } 13 | 14 | public void ToArraySelect() 15 | { 16 | var str = "string"; 17 | 18 | var result = str.ToArray().Any(o => o != ' '); 19 | } 20 | 21 | public void ToListSelect() 22 | { 23 | var str = "string"; 24 | 25 | var result = str.ToList().Any(); 26 | } 27 | 28 | public void GetStringToCharArraySelect() 29 | { 30 | var result = GetString().ToCharArray().Select(o => o); 31 | } 32 | 33 | public void GetStringToArraySelect() 34 | { 35 | var result = GetString().ToArray().Select(o => o); 36 | } 37 | 38 | private static string GetString() 39 | { 40 | return "str"; 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /Tests/Resources/ConstructorAfter.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class Constructor 7 | { 8 | public void ManyArgumentsConstructor() 9 | { 10 | var list = System.Linq.Enumerable.Empty(); 11 | 12 | var obj = new MyClass(list, false, GetList()); 13 | } 14 | 15 | private static IEnumerable GetList() 16 | { 17 | return System.Linq.Enumerable.Empty(); 18 | } 19 | 20 | private class MyClass 21 | { 22 | private readonly IEnumerable source; 23 | 24 | public MyClass(IEnumerable source) 25 | { 26 | source = source; 27 | } 28 | 29 | public MyClass(IEnumerable source, bool value, IEnumerable test) 30 | { 31 | source = source; 32 | if (value) 33 | { 34 | source = test; 35 | } 36 | } 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Sergey Rogatnev 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Tests/Resources/Constructor2.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class Constructor 7 | { 8 | public void ManyArgumentsConstructor() 9 | { 10 | var list = System.Linq.Enumerable.Empty(); 11 | 12 | var obj = new MyClass(list.ToArray(), false, GetList().ToArray()); 13 | } 14 | 15 | private static IEnumerable GetList() 16 | { 17 | return System.Linq.Enumerable.Empty(); 18 | } 19 | 20 | private class MyClass 21 | { 22 | private readonly IEnumerable source; 23 | 24 | public MyClass(IEnumerable source) 25 | { 26 | source = source; 27 | } 28 | 29 | public MyClass(IEnumerable source, bool value, IEnumerable test) 30 | { 31 | source = source; 32 | if (value) 33 | { 34 | source = test; 35 | } 36 | } 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /Tests/Resources/Constructor3.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class Constructor 7 | { 8 | public void ManyArgumentsConstructor() 9 | { 10 | var list = System.Linq.Enumerable.Empty(); 11 | 12 | var obj = new MyClass(list.ToArray(), false, GetList().ToArray()); 13 | } 14 | 15 | private static IEnumerable GetList() 16 | { 17 | return System.Linq.Enumerable.Empty(); 18 | } 19 | 20 | private class MyClass 21 | { 22 | private readonly IEnumerable source; 23 | 24 | public MyClass(IEnumerable source) 25 | { 26 | source = source; 27 | } 28 | 29 | public MyClass(T[] source, bool value, IReadOnlyCollection test) 30 | { 31 | source = source; 32 | if (value) 33 | { 34 | source = test.ToArray(); 35 | } 36 | } 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /Tests/Resources/ConstructorBefore.txt: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class Constructor 7 | { 8 | public void ManyArgumentsConstructor() 9 | { 10 | var list = System.Linq.Enumerable.Empty(); 11 | 12 | var obj = new MyClass({|CI0003:list.ToArray()|}, false, {|CI0003:GetList().ToArray()|}); 13 | } 14 | 15 | private static IEnumerable GetList() 16 | { 17 | return System.Linq.Enumerable.Empty(); 18 | } 19 | 20 | private class MyClass 21 | { 22 | private readonly IEnumerable source; 23 | 24 | public MyClass(IEnumerable source) 25 | { 26 | source = source; 27 | } 28 | 29 | public MyClass(IEnumerable source, bool value, IEnumerable test) 30 | { 31 | source = source; 32 | if (value) 33 | { 34 | source = test; 35 | } 36 | } 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /Tests/StringTests/StringJoinToArrayConversionTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0003; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.StringTests; 9 | 10 | public class StringJoinToArrayConversionTests : CSharpCodeFixTest 12 | { 13 | [Test] 14 | public Task StringJoinToArrayTest() 15 | { 16 | var code = ResourceReader.ReadFromFile("StringJoin1.txt"); 17 | 18 | return StringJoinToArrayConversionVerifier 19 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0003").WithSpan(11, 44, 11, 78)); 20 | } 21 | 22 | [TestCase("StringJoinBefore.txt", "StringJoinAfter.txt")] 23 | public Task CodeFixesTest(string before, string after) 24 | { 25 | var code = ResourceReader.ReadFromFile(before); 26 | var fixedCode = ResourceReader.ReadFromFile(after); 27 | 28 | return StringJoinToArrayConversionVerifier.VerifyCodeFixAsync(code, fixedCode); 29 | } 30 | } -------------------------------------------------------------------------------- /Documentation/CI0001.md: -------------------------------------------------------------------------------- 1 | # CI0001: Redundant string conversion 2 | Redundant string conversion to `char[]` or `List`. 3 | 4 | ## Examples 5 | ### foreach statement 6 | 7 | ```csharp 8 | var str = "string"; 9 | 10 | foreach (var c in str.ToArray()) 11 | { 12 | Console.WriteLine(c); 13 | } 14 | 15 | foreach (var c in str.ToCharArray()) 16 | { 17 | Console.WriteLine(c); 18 | } 19 | 20 | foreach (var c in str.ToList()) 21 | { 22 | Console.WriteLine(c); 23 | } 24 | ``` 25 | 26 | ``` 27 | public static void ForeachToArrayGetString() 28 | { 29 | foreach (var c in GetString().ToArray()) 30 | { 31 | Console.WriteLine(c); 32 | } 33 | } 34 | 35 | private static string GetString() 36 | { 37 | return "str"; 38 | } 39 | ``` 40 | 41 | ### LINQ-methods 42 | ``` 43 | var str = "string"; 44 | 45 | var result1 = str.ToCharArray().Select(o => o); 46 | 47 | var result2 = str.ToArray().Any(o => o != ' '); 48 | 49 | var result3 = str.ToList().Any(); 50 | ``` 51 | 52 | ``` 53 | public void GetStringToCharArraySelect() 54 | { 55 | var result = GetString().ToCharArray().Select(o => o); 56 | } 57 | 58 | private static string GetString() 59 | { 60 | return "str"; 61 | } 62 | ``` -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 0.2.13 2 | Added [CI0008](https://github.com/Backs/Collections.Analyzer/blob/master/Documentation/CI0008.md): Diagnostic to suggest using HashSet instead of array for Contains operations. HashSet provides O(1) lookup performance compared to O(n) for arrays. 3 | 4 | ## 0.2.12.1 5 | Concurrent collections improvements. 6 | 7 | ## 0.2.12 8 | Added concurrent collections diagnostic [CI0007](https://github.com/Backs/Collections.Analyzer/blob/master/Documentation/CI0007.md) 9 | 10 | ## 0.2.11 11 | Added collection initializer diagnostic to [CI0006](https://github.com/Backs/Collections.Analyzer/blob/master/Documentation/CI0006.md) 12 | 13 | ## 0.2.8.1 14 | Fix variable initializer. 15 | 16 | ## 0.2.8 17 | Added variable initializer diagnostic to [CI0003](https://github.com/Backs/Collections.Analyzer/blob/master/Documentation/CI0003.md) 18 | 19 | ## 0.2.7.1: 20 | Fix object initializer diagnostic. 21 | 22 | ## 0.2.7: 23 | 24 | Added object initializer diagnostic to [CI0003](https://github.com/Backs/Collections.Analyzer/blob/master/Documentation/CI0003.md) 25 | 26 | ## 0.2.6: 27 | 28 | Added property diagnostic to [CI0003](https://github.com/Backs/Collections.Analyzer/blob/master/Documentation/CI0003.md) 29 | -------------------------------------------------------------------------------- /Tests/ArrayTests/ObjectInitializerTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0003; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.ArrayTests; 9 | 10 | [TestFixture] 11 | public class ObjectInitializerTests : CSharpCodeFixTest 13 | { 14 | [Test] 15 | public Task ObjectInitializerTest() 16 | { 17 | var code = ResourceReader.ReadFromFile("ObjectInitializer.txt"); 18 | 19 | return ObjectInitializerVerifier 20 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0003").WithSpan(15, 30, 15, 61), DiagnosticResult.CompilerWarning("CI0003").WithSpan(16, 30, 16, 61)); 21 | } 22 | 23 | [Test] 24 | [TestCase("ObjectInitializerBefore.txt", "ObjectInitializerAfter.txt")] 25 | public Task CodeFixesTest(string before, string after) 26 | { 27 | var code = ResourceReader.ReadFromFile(before); 28 | var fixedCode = ResourceReader.ReadFromFile(after); 29 | 30 | return ObjectInitializerVerifier.VerifyCodeFixAsync(code, fixedCode); 31 | } 32 | } -------------------------------------------------------------------------------- /Tests/ArrayTests/AddRangeTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0003; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.ArrayTests; 9 | 10 | public class AddRangeTests : CSharpCodeFixTest 12 | { 13 | [Test] 14 | public Task AddRange1Test() 15 | { 16 | var code = ResourceReader.ReadFromFile("AddRange1.txt"); 17 | 18 | return AddRangeVerifier 19 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0003").WithSpan(13, 27, 13, 42)); 20 | } 21 | 22 | [Test] 23 | public Task AddRange2Test() 24 | { 25 | var code = ResourceReader.ReadFromFile("AddRange2.txt"); 26 | 27 | return AddRangeVerifier 28 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0003").WithSpan(12, 27, 12, 47)); 29 | } 30 | 31 | [Test] 32 | [TestCase("AddRangeBefore.txt", "AddRangeAfter.txt")] 33 | public Task CodeFixesTest(string before, string after) 34 | { 35 | var code = ResourceReader.ReadFromFile(before); 36 | var fixedCode = ResourceReader.ReadFromFile(after); 37 | 38 | return AddRangeVerifier.VerifyCodeFixAsync(code, fixedCode); 39 | } 40 | } -------------------------------------------------------------------------------- /Examples/ConcurrentCollections/ConcurrentBagIsEmpty.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | 4 | namespace Examples.ConcurrentCollections; 5 | 6 | public class ConcurrentBagIsEmpty 7 | { 8 | public bool Method1() 9 | { 10 | var bag = new ConcurrentBag(new[] { "a", "b", "c" }); 11 | 12 | return bag.Any(); 13 | } 14 | 15 | public bool Method2() 16 | { 17 | var bag = new ConcurrentBag(new[] { "a", "b", "c" }); 18 | 19 | return bag.Any(o => o == "d"); 20 | } 21 | 22 | public bool Method3() 23 | { 24 | return GetBag().Any(); 25 | } 26 | 27 | private static ConcurrentBag GetBag() 28 | { 29 | return new ConcurrentBag(new[] { "a", "b", "c" }); 30 | } 31 | 32 | public bool Method4() 33 | { 34 | var bag = new ConcurrentBag(new[] { "a", "b", "c" }); 35 | 36 | return !bag.Any(); 37 | } 38 | 39 | public void Method5() 40 | { 41 | var bag = new ConcurrentBag(new[] { "a", "b", "c" }); 42 | 43 | var isEmpty = !bag.Any(); 44 | } 45 | 46 | public void Method6() 47 | { 48 | var bag = new ConcurrentBag(new[] { "a", "b", "c" }); 49 | 50 | WithEmpty(bag.Any()); 51 | } 52 | 53 | private void WithEmpty(bool b) 54 | { 55 | throw new System.NotImplementedException(); 56 | } 57 | } -------------------------------------------------------------------------------- /Tests/ListTests/ListCapacityTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0006; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.ListTests; 9 | 10 | [TestFixture] 11 | public class ListCapacityTests : CSharpCodeFixTest< 12 | ListInitializerDiagnostic, SetListCapacityCodeFix, DefaultVerifier> 13 | { 14 | [Test] 15 | public Task ListCapacityTest() 16 | { 17 | var code = ResourceReader.ReadFromFile("ListInitializer1.txt"); 18 | 19 | return ListCapacityVerifier 20 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0006").WithSpan(9, 25, 9, 51)); 21 | } 22 | 23 | [Test] 24 | public Task ListLessCapacityTest() 25 | { 26 | var code = ResourceReader.ReadFromFile("ListInitializer2.txt"); 27 | 28 | return ListCapacityVerifier 29 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0006").WithSpan(9, 25, 9, 54)); 30 | } 31 | 32 | [Test] 33 | [TestCase("ListInitializerBefore1.txt", "ListInitializerAfter1.txt")] 34 | [TestCase("ListInitializerBefore2.txt", "ListInitializerAfter2.txt")] 35 | public Task CodeFixesTest(string before, string after) 36 | { 37 | var code = ResourceReader.ReadFromFile(before); 38 | var fixedCode = ResourceReader.ReadFromFile(after); 39 | 40 | return ListCapacityVerifier.VerifyCodeFixAsync(code, fixedCode); 41 | } 42 | } -------------------------------------------------------------------------------- /Examples/Arrays/ArrayToArray.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace Examples.Arrays 6 | { 7 | public class ArrayToArray 8 | { 9 | public static void Convert() 10 | { 11 | var array = Array.Empty(); 12 | var result = array.ToArray(); 13 | } 14 | 15 | public static void ConvertFromMethod() 16 | { 17 | var result = GetArray().ToArray(); 18 | } 19 | 20 | public static void ConvertFromProperty() 21 | { 22 | var result = ArrayProperty.ToArray(); 23 | } 24 | 25 | private static int[] ArrayProperty => Array.Empty(); 26 | 27 | private static int[] GetArray() 28 | { 29 | return Array.Empty(); 30 | } 31 | 32 | private static void Initialize() 33 | { 34 | var value1 = new MyClass 35 | { 36 | ArrayProperty = Array.Empty(), 37 | EnumerableProperty = Array.Empty() 38 | }; 39 | 40 | var value2 = new MyClass 41 | { 42 | ArrayProperty = value1.ArrayProperty.ToArray(), 43 | EnumerableProperty = value1.EnumerableProperty.ToList() 44 | }; 45 | } 46 | 47 | private class MyClass 48 | { 49 | public int[] ArrayProperty { get; set; } = null!; 50 | public IEnumerable EnumerableProperty { get; set; } = null!; 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /Tests/StringTests/ListFromStringTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0004; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.StringTests; 9 | 10 | public class ListFromStringTests : CSharpCodeFixTest 12 | { 13 | [Test] 14 | public Task ListConstructor1Test() 15 | { 16 | var code = ResourceReader.ReadFromFile("StringListConstructor1.txt"); 17 | 18 | return ListFromStringVerifier 19 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0004").WithSpan(12, 41, 12, 54)); 20 | } 21 | 22 | [Test] 23 | public Task ListConstructor2Test() 24 | { 25 | var code = ResourceReader.ReadFromFile("StringListConstructor2.txt"); 26 | 27 | return ListFromStringVerifier 28 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0004").WithSpan(12, 41, 12, 44)); 29 | } 30 | 31 | [TestCase("StringListConstructorBefore1.txt", "StringListConstructorAfter.txt")] 32 | [TestCase("StringListConstructorBefore2.txt", "StringListConstructorAfter.txt")] 33 | public Task CodeFixesTest(string before, string after) 34 | { 35 | var code = ResourceReader.ReadFromFile(before); 36 | var fixedCode = ResourceReader.ReadFromFile(after); 37 | 38 | return ListFromStringVerifier.VerifyCodeFixAsync(code, fixedCode); 39 | } 40 | } -------------------------------------------------------------------------------- /Benchmarks/InitListBenchmark.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using BenchmarkDotNet.Attributes; 3 | using BenchmarkDotNet.Jobs; 4 | 5 | namespace Benchmarks 6 | { 7 | [ShortRunJob(RuntimeMoniker.Net48)] 8 | [ShortRunJob(RuntimeMoniker.Net60)] 9 | [ShortRunJob(RuntimeMoniker.Net80)] 10 | [MemoryDiagnoser] 11 | public class InitListBenchmark 12 | { 13 | [BenchmarkCategory("One")] 14 | [Benchmark] 15 | public List InitList1() 16 | { 17 | return new List {1}; 18 | } 19 | 20 | [BenchmarkCategory("One")] 21 | [Benchmark] 22 | public List InitListWithSize1() 23 | { 24 | return new List(1) {1}; 25 | } 26 | 27 | [BenchmarkCategory("Five")] 28 | [Benchmark] 29 | public List InitList5() 30 | { 31 | return new List {1, 2, 3, 4, 5}; 32 | } 33 | 34 | [BenchmarkCategory("Five")] 35 | [Benchmark] 36 | public List InitListWithSize5() 37 | { 38 | return new List(5) {1, 2, 3, 4, 5}; 39 | } 40 | 41 | [BenchmarkCategory("Ten")] 42 | [Benchmark] 43 | public List InitList10() 44 | { 45 | return new List {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; 46 | } 47 | 48 | [BenchmarkCategory("Ten")] 49 | [Benchmark] 50 | public List InitListWithSize10() 51 | { 52 | return new List(10) {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /Collections.Analyzer/Diagnostics/ExpressionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using Microsoft.CodeAnalysis; 4 | using Microsoft.CodeAnalysis.CSharp; 5 | using Microsoft.CodeAnalysis.CSharp.Syntax; 6 | using Microsoft.CodeAnalysis.Diagnostics; 7 | 8 | namespace Collections.Analyzer.Diagnostics 9 | { 10 | public static class ExpressionExtensions 11 | { 12 | private static readonly IReadOnlyCollection Methods = 13 | new HashSet(new[] {nameof(Enumerable.ToArray), nameof(Enumerable.ToList)}); 14 | 15 | public static bool IsRedundantMethod(SyntaxNodeAnalysisContext context, 16 | ExpressionSyntax invocationExpression) 17 | { 18 | return context.SemanticModel.GetSymbolInfo(invocationExpression).Symbol is IMethodSymbol redundantMethod && 19 | Methods.Contains(redundantMethod.Name); 20 | } 21 | 22 | public static ITypeSymbol? GetCallerType(SyntaxNodeAnalysisContext context, 23 | InvocationExpressionSyntax invocationExpression) 24 | { 25 | if (invocationExpression.Expression is not MemberAccessExpressionSyntax memberAccessExpression) 26 | return null; 27 | var symbol = context.SemanticModel.GetSymbolInfo(memberAccessExpression.Expression).Symbol; 28 | 29 | return symbol switch 30 | { 31 | ILocalSymbol localSymbol => localSymbol.Type, 32 | IMethodSymbol methodSymbol => methodSymbol.ReturnType, 33 | _ => null 34 | }; 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Tests/ArrayTests/RedundantArrayToArrayConversionTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0002; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.ArrayTests; 9 | 10 | public class RedundantArrayToArrayConversionTests : CSharpCodeFixTest 12 | { 13 | [Test] 14 | public Task ArrayToArrayTest() 15 | { 16 | var code = ResourceReader.ReadFromFile("ArrayToArray.txt"); 17 | 18 | return RedundantArrayToArrayConversionVerifier 19 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0002").WithSpan(11, 26, 11, 41)); 20 | } 21 | 22 | [Test] 23 | public Task GetArrayToArrayTest() 24 | { 25 | var code = ResourceReader.ReadFromFile("GetArrayToArray.txt"); 26 | 27 | return RedundantArrayToArrayConversionVerifier 28 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0002").WithSpan(10, 26, 10, 46)); 29 | } 30 | 31 | [Test] 32 | [TestCase("ArrayToArrayBefore.txt", "ArrayToArrayAfter.txt")] 33 | [TestCase("GetArrayToArrayBefore.txt", "GetArrayToArrayAfter.txt")] 34 | public Task CodeFixesTest(string before, string after) 35 | { 36 | var code = ResourceReader.ReadFromFile(before); 37 | var fixedCode = ResourceReader.ReadFromFile(after); 38 | 39 | return RedundantArrayToArrayConversionVerifier.VerifyCodeFixAsync(code, fixedCode); 40 | } 41 | } -------------------------------------------------------------------------------- /Tests/EnumerableTests/AssignEnumerableTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0003; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.EnumerableTests; 9 | 10 | [TestFixture] 11 | public class AssignEnumerableTests : CSharpCodeFixTest< 12 | AssignEnumerableDiagnostic, 13 | RemoveRedundantMethodCallCodeFix, DefaultVerifier> 14 | { 15 | [Test] 16 | public Task AssignEnumerable1Test() 17 | { 18 | var code = ResourceReader.ReadFromFile("AssignEnumerable1.txt"); 19 | 20 | return AssignEnumerableVerifier 21 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0003").WithSpan(11, 39, 11, 59)); 22 | } 23 | 24 | [Test] 25 | public Task AssignEnumerable2Test() 26 | { 27 | var code = ResourceReader.ReadFromFile("AssignEnumerable2.txt"); 28 | 29 | return AssignEnumerableVerifier 30 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0003").WithSpan(10, 39, 10, 59)); 31 | } 32 | 33 | [Test] 34 | [TestCase("AssignEnumerableBefore1.txt", "AssignEnumerableAfter1.txt")] 35 | [TestCase("AssignEnumerableBefore2.txt", "AssignEnumerableAfter2.txt")] 36 | public Task CodeFixesTest(string before, string after) 37 | { 38 | var code = ResourceReader.ReadFromFile(before); 39 | var fixedCode = ResourceReader.ReadFromFile(after); 40 | 41 | return AssignEnumerableVerifier.VerifyCodeFixAsync(code, fixedCode); 42 | } 43 | } -------------------------------------------------------------------------------- /Examples/Enumerable/Constructor.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace Examples.Enumerable 5 | { 6 | public class Constructor 7 | { 8 | public void CallConstructor() 9 | { 10 | var enumerable = System.Linq.Enumerable.Empty(); 11 | 12 | var obj = new MyClass(enumerable.ToList()); 13 | } 14 | 15 | public void ManyArgumentsConstructor() 16 | { 17 | ICollection list = new Constructor[10]; 18 | 19 | var obj = new MyClass(list.ToArray(), false, GetEnumerable().ToArray()); 20 | } 21 | 22 | public void ArrayTest() 23 | { 24 | var list = new List(); 25 | 26 | var obj = new MyClass(list.ToArray(), true); 27 | } 28 | 29 | private static IEnumerable GetEnumerable() 30 | { 31 | return System.Linq.Enumerable.Empty(); 32 | } 33 | 34 | private class MyClass 35 | { 36 | private readonly IEnumerable source = null!; 37 | 38 | public MyClass(IEnumerable source) 39 | { 40 | this.source = source; 41 | } 42 | 43 | public MyClass(ICollection source) 44 | { 45 | this.source = source; 46 | } 47 | 48 | public MyClass(IEnumerable source, bool value, IReadOnlyCollection test) 49 | { 50 | this.source = source; 51 | if (value) this.source = test; 52 | } 53 | 54 | public MyClass(T[] source, bool value) 55 | { 56 | this.source = source; 57 | if (value) this.source = null!; 58 | } 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /Tests/ArrayTests/ConstructorTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0003; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.ArrayTests; 9 | 10 | public class ConstructorTests : CSharpCodeFixTest 12 | { 13 | [Test] 14 | [TestCase("Constructor1.txt")] 15 | [TestCase("Constructor4.txt")] 16 | public Task ConstructorTest(string fileName) 17 | { 18 | var code = ResourceReader.ReadFromFile(fileName); 19 | 20 | return ConstructorVerifier 21 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0003").WithSpan(12, 40, 12, 54)); 22 | } 23 | 24 | [Test] 25 | public Task ManyArgumentsTest() 26 | { 27 | var code = ResourceReader.ReadFromFile("Constructor2.txt"); 28 | 29 | return ConstructorVerifier 30 | .VerifyAnalyzerAsync(code, 31 | DiagnosticResult.CompilerWarning("CI0003").WithSpan(12, 48, 12, 62), 32 | DiagnosticResult.CompilerWarning("CI0003").WithSpan(12, 71, 12, 90)); 33 | } 34 | 35 | [Test] 36 | public Task NoErrorTest() 37 | { 38 | var code = ResourceReader.ReadFromFile("Constructor3.txt"); 39 | 40 | return ConstructorVerifier 41 | .VerifyAnalyzerAsync(code); 42 | } 43 | 44 | [Test] 45 | [TestCase("ConstructorBefore.txt", "ConstructorAfter.txt")] 46 | public Task CodeFixesTest(string before, string after) 47 | { 48 | var code = ResourceReader.ReadFromFile(before); 49 | var fixedCode = ResourceReader.ReadFromFile(after); 50 | 51 | return ConstructorVerifier.VerifyCodeFixAsync(code, fixedCode); 52 | } 53 | } -------------------------------------------------------------------------------- /Documentation/Diagnostics.md: -------------------------------------------------------------------------------- 1 | | Id | Title | Severity | Description | 2 | |---------------------|-------------------------------------------------|----------|-----------------------------------------------------------------------------------------------------| 3 | | [CI0001](CI0001.md) | Redundant string conversion | Warning | Redundant string conversion to `char[]` or `List` | 4 | | [CI0002](CI0002.md) | Redundant array conversion | Warning | Redundant `ToArray` method call on array | 5 | | [CI0003](CI0003.md) | Redundant enumerable conversion | Warning | Redundant `ToArray` or `ToList` method call on types that implements `IEnumerable` interface | 6 | | [CI0004](CI0004.md) | Not optimal `List` constructor usage | Warning | String parameter for `List` constructor is better to use with `ToCharArray` call | 7 | | [CI0005](CI0005.md) | Not optimal count of collection items | Warning | It's better to use LINQ method `Count()` instead of calling `ToArray()` and using property `Length` | 8 | | [CI0006](CI0006.md) | Collection initializer is used without capacity | Warning | Set initial capacity with collection initializer | 9 | | [CI0007](CI0007.md) | Method `Any()` is used on concurrent collection | Warning | Use `IsEmpty` property to check empty collection | 10 | | [CI0008](CI0008.md) | Consider using HashSet for Contains operations | Warning | Array is used with `Contains()` method. `HashSet` provides O(1) lookup performance | 11 | -------------------------------------------------------------------------------- /Tests/ConcurrentBagIsEmptyTests/IsEmptyTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0007; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.ConcurrentBagIsEmptyTests; 9 | 10 | [TestFixture] 11 | public class IsEmptyTests: CSharpCodeFixTest< 12 | ConcurrentCollectionIsEmptyDiagnostic, ReplaceAnyWithIsEmptyCodeFix, DefaultVerifier> 13 | { 14 | [Test] 15 | public Task LocalVariableIsEmptyTest() 16 | { 17 | var code = ResourceReader.ReadFromFile("ConcurrentBag1.txt"); 18 | 19 | return ConcurrentBagIsEmptyVerifier 20 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0007").WithSpan(12, 20, 12, 27)); 21 | } 22 | 23 | [Test] 24 | public Task ReturnValueIsEmptyTest() 25 | { 26 | var code = ResourceReader.ReadFromFile("ConcurrentBag2.txt"); 27 | 28 | return ConcurrentBagIsEmptyVerifier 29 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0007").WithSpan(10, 20, 10, 32)); 30 | } 31 | 32 | [Test] 33 | public Task IsEmptyNoWarnTest() 34 | { 35 | var code = ResourceReader.ReadFromFile("ConcurrentBag3.txt"); 36 | 37 | return ConcurrentBagIsEmptyVerifier 38 | .VerifyAnalyzerAsync(code, DiagnosticResult.EmptyDiagnosticResults); 39 | } 40 | 41 | [Test] 42 | [TestCase("ConcurrentBagBefore1.txt", "ConcurrentBagAfter1.txt")] 43 | [TestCase("ConcurrentBagBefore2.txt", "ConcurrentBagAfter2.txt")] 44 | [TestCase("ConcurrentBagBefore3.txt", "ConcurrentBagAfter3.txt")] 45 | [TestCase("ConcurrentBagBefore4.txt", "ConcurrentBagAfter4.txt")] 46 | public Task CodeFixesTest(string before, string after) 47 | { 48 | var code = ResourceReader.ReadFromFile(before); 49 | var fixedCode = ResourceReader.ReadFromFile(after); 50 | 51 | return ConcurrentBagIsEmptyVerifier.VerifyCodeFixAsync(code, fixedCode); 52 | } 53 | } -------------------------------------------------------------------------------- /Tests/ConcurrentQueueIsEmptyTests/IsEmptyTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0007; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.ConcurrentQueueIsEmptyTests; 9 | 10 | [TestFixture] 11 | public class IsEmptyTests: CSharpCodeFixTest< 12 | ConcurrentCollectionIsEmptyDiagnostic, ReplaceAnyWithIsEmptyCodeFix, DefaultVerifier> 13 | { 14 | [Test] 15 | public Task LocalVariableIsEmptyTest() 16 | { 17 | var code = ResourceReader.ReadFromFile("ConcurrentQueue1.txt"); 18 | 19 | return ConcurrentQueueIsEmptyVerifier 20 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0007").WithSpan(12, 20, 12, 29)); 21 | } 22 | 23 | [Test] 24 | public Task ReturnValueIsEmptyTest() 25 | { 26 | var code = ResourceReader.ReadFromFile("ConcurrentQueue2.txt"); 27 | 28 | return ConcurrentQueueIsEmptyVerifier 29 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0007").WithSpan(10, 20, 10, 34)); 30 | } 31 | 32 | [Test] 33 | public Task IsEmptyNoWarnTest() 34 | { 35 | var code = ResourceReader.ReadFromFile("ConcurrentQueue3.txt"); 36 | 37 | return ConcurrentQueueIsEmptyVerifier 38 | .VerifyAnalyzerAsync(code, DiagnosticResult.EmptyDiagnosticResults); 39 | } 40 | 41 | [Test] 42 | [TestCase("ConcurrentQueueBefore1.txt", "ConcurrentQueueAfter1.txt")] 43 | [TestCase("ConcurrentQueueBefore2.txt", "ConcurrentQueueAfter2.txt")] 44 | [TestCase("ConcurrentQueueBefore3.txt", "ConcurrentQueueAfter3.txt")] 45 | [TestCase("ConcurrentQueueBefore4.txt", "ConcurrentQueueAfter4.txt")] 46 | public Task CodeFixesTest(string before, string after) 47 | { 48 | var code = ResourceReader.ReadFromFile(before); 49 | var fixedCode = ResourceReader.ReadFromFile(after); 50 | 51 | return ConcurrentQueueIsEmptyVerifier.VerifyCodeFixAsync(code, fixedCode); 52 | } 53 | } -------------------------------------------------------------------------------- /Tests/ConcurrentStackIsEmptyTests/IsEmptyTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0007; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.ConcurrentStackIsEmptyTests; 9 | 10 | [TestFixture] 11 | public class IsEmptyTests: CSharpCodeFixTest< 12 | ConcurrentCollectionIsEmptyDiagnostic, ReplaceAnyWithIsEmptyCodeFix, DefaultVerifier> 13 | { 14 | [Test] 15 | public Task LocalVariableIsEmptyTest() 16 | { 17 | var code = ResourceReader.ReadFromFile("ConcurrentStack1.txt"); 18 | 19 | return ConcurrentStackIsEmptyVerifier 20 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0007").WithSpan(12, 20, 12, 29)); 21 | } 22 | 23 | [Test] 24 | public Task ReturnValueIsEmptyTest() 25 | { 26 | var code = ResourceReader.ReadFromFile("ConcurrentStack2.txt"); 27 | 28 | return ConcurrentStackIsEmptyVerifier 29 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0007").WithSpan(10, 20, 10, 34)); 30 | } 31 | 32 | [Test] 33 | public Task IsEmptyNoWarnTest() 34 | { 35 | var code = ResourceReader.ReadFromFile("ConcurrentStack3.txt"); 36 | 37 | return ConcurrentStackIsEmptyVerifier 38 | .VerifyAnalyzerAsync(code, DiagnosticResult.EmptyDiagnosticResults); 39 | } 40 | 41 | [Test] 42 | [TestCase("ConcurrentStackBefore1.txt", "ConcurrentStackAfter1.txt")] 43 | [TestCase("ConcurrentStackBefore2.txt", "ConcurrentStackAfter2.txt")] 44 | [TestCase("ConcurrentStackBefore3.txt", "ConcurrentStackAfter3.txt")] 45 | [TestCase("ConcurrentStackBefore4.txt", "ConcurrentStackAfter4.txt")] 46 | public Task CodeFixesTest(string before, string after) 47 | { 48 | var code = ResourceReader.ReadFromFile(before); 49 | var fixedCode = ResourceReader.ReadFromFile(after); 50 | 51 | return ConcurrentStackIsEmptyVerifier.VerifyCodeFixAsync(code, fixedCode); 52 | } 53 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![MIT](https://img.shields.io/github/license/Backs/Collections.Analyzer)](LICENSE) 2 | [![Nuget](https://img.shields.io/nuget/v/Collections.Analyzer)](https://www.nuget.org/packages/Collections.Analyzer/) 3 | 4 | Collections.Analyzer is a set of roslyn-based diagnostics for C#-projects that detect potential problems with operating 5 | different collections. 6 | 7 | # Motivation 8 | 9 | For more information, see the following articles: 10 | 11 | - [Part 1: string to array of chars](https://blog.rogatnev.net/posts/2021/09/Harmful-collection-transformations-part-1-strings.html) 12 | - [Part 2: automatic diagnostics](https://blog.rogatnev.net/posts/2021/10/Harmful-collection-transformations-part-2-diagnostics.html) 13 | - [Part 3: collections](https://blog.rogatnev.net/posts/2022/01/Harmful-collection-transformations-part-3-collections.html) 14 | 15 | # Features 16 | 17 | ### Compiler warnings 18 | 19 | Analyze your C#-code and warn about redundant method calls. 20 | 21 | ![Code fix string](https://raw.githubusercontent.com/Backs/Collections.Analyzer/master/Documentation/img/string-example-2.png) 22 | 23 | ### Code fixes 24 | 25 | Automatically fixes found problems. 26 | 27 | ![Code fix enumerable](https://raw.githubusercontent.com/Backs/Collections.Analyzer/master/Documentation/img/enumerable-example-1.gif) 28 | 29 | # Diagnostics 30 | 31 | [Full set of diagnostics](https://github.com/Backs/Collections.Analyzer/blob/master/Documentation/Diagnostics.md) 32 | 33 | # Installation 34 | 35 | Every analyzer can be installed as a usual nuget-package. Just add a package reference to a project: 36 | 37 | ``` 38 | 39 | ``` 40 | 41 | The analyzer will work only in the project it was added to. If you want to analyse all projects in your solution, you 42 | can add file `Directory.build.props` to the solution directory with content: 43 | 44 | ``` 45 | 46 | 47 | 48 | 49 | 50 | ``` 51 | 52 | MSBuild will read these properties. -------------------------------------------------------------------------------- /Tests/ConcurrentDictionaryIsEmptyTests/IsEmptyTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0007; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.ConcurrentDictionaryIsEmptyTests; 9 | 10 | [TestFixture] 11 | public class IsEmptyTests : CSharpCodeFixTest< 12 | ConcurrentCollectionIsEmptyDiagnostic, ReplaceAnyWithIsEmptyCodeFix, DefaultVerifier> 13 | { 14 | [Test] 15 | public Task LocalVariableIsEmptyTest() 16 | { 17 | var code = ResourceReader.ReadFromFile("ConcurrentDictionary1.txt"); 18 | 19 | return ConcurrentDictionaryIsEmptyVerifier 20 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0007").WithSpan(15, 20, 15, 28)); 21 | } 22 | 23 | [Test] 24 | public Task ReturnValueIsEmptyTest() 25 | { 26 | var code = ResourceReader.ReadFromFile("ConcurrentDictionary3.txt"); 27 | 28 | return ConcurrentDictionaryIsEmptyVerifier 29 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0007").WithSpan(10, 20, 10, 33)); 30 | } 31 | 32 | [Test] 33 | public Task IsEmptyNoWarnTest() 34 | { 35 | var code = ResourceReader.ReadFromFile("ConcurrentDictionary2.txt"); 36 | 37 | return ConcurrentDictionaryIsEmptyVerifier 38 | .VerifyAnalyzerAsync(code, DiagnosticResult.EmptyDiagnosticResults); 39 | } 40 | 41 | [Test] 42 | [TestCase("ConcurrentDictionaryBefore1.txt", "ConcurrentDictionaryAfter1.txt")] 43 | [TestCase("ConcurrentDictionaryBefore2.txt", "ConcurrentDictionaryAfter2.txt")] 44 | [TestCase("ConcurrentDictionaryBefore3.txt", "ConcurrentDictionaryAfter3.txt")] 45 | [TestCase("ConcurrentDictionaryBefore4.txt", "ConcurrentDictionaryAfter4.txt")] 46 | public Task CodeFixesTest(string before, string after) 47 | { 48 | var code = ResourceReader.ReadFromFile(before); 49 | var fixedCode = ResourceReader.ReadFromFile(after); 50 | 51 | return ConcurrentDictionaryIsEmptyVerifier.VerifyCodeFixAsync(code, fixedCode); 52 | } 53 | } -------------------------------------------------------------------------------- /Collections.Analyzer/Diagnostics/CI0003/AddRangeDiagnostic.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.Immutable; 3 | using Microsoft.CodeAnalysis; 4 | using Microsoft.CodeAnalysis.CSharp; 5 | using Microsoft.CodeAnalysis.CSharp.Syntax; 6 | using Microsoft.CodeAnalysis.Diagnostics; 7 | 8 | namespace Collections.Analyzer.Diagnostics.CI0003 9 | { 10 | [DiagnosticAnalyzer(LanguageNames.CSharp)] 11 | public class AddRangeDiagnostic : DiagnosticAnalyzer 12 | { 13 | internal static readonly DiagnosticDescriptor AddRangeRule = new( 14 | "CI0003", 15 | Resources.CI0003_Title, 16 | Resources.CI0003_Title, 17 | Categories.Performance, 18 | DiagnosticSeverity.Warning, 19 | true 20 | ); 21 | 22 | public override ImmutableArray SupportedDiagnostics => 23 | ImmutableArray.Create(AddRangeRule); 24 | 25 | public override void Initialize(AnalysisContext context) 26 | { 27 | context.EnableConcurrentExecution(); 28 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); 29 | 30 | context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression); 31 | } 32 | 33 | private static void Analyze(SyntaxNodeAnalysisContext context) 34 | { 35 | var invocationExpression = (InvocationExpressionSyntax) context.Node; 36 | 37 | if (!ExpressionExtensions.IsRedundantMethod(context, invocationExpression)) return; 38 | 39 | if (invocationExpression.Parent is ArgumentSyntax argument && 40 | argument.Parent is ArgumentListSyntax argumentList && 41 | argumentList.Parent is InvocationExpressionSyntax identifier && 42 | identifier.Expression is MemberAccessExpressionSyntax memberAccessExpression && 43 | memberAccessExpression.Name.ToString() == nameof(List.AddRange)) 44 | context.ReportDiagnostic(Diagnostic.Create(AddRangeRule, invocationExpression.GetLocation(), 45 | invocationExpression.ToString())); 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /Collections.Analyzer/Diagnostics/CI0003/StringJoinToArrayDiagnostic.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using System.Linq; 3 | using Microsoft.CodeAnalysis; 4 | using Microsoft.CodeAnalysis.CSharp; 5 | using Microsoft.CodeAnalysis.CSharp.Syntax; 6 | using Microsoft.CodeAnalysis.Diagnostics; 7 | 8 | namespace Collections.Analyzer.Diagnostics.CI0003 9 | { 10 | [DiagnosticAnalyzer(LanguageNames.CSharp)] 11 | public class StringJoinToArrayDiagnostic : DiagnosticAnalyzer 12 | { 13 | internal static readonly DiagnosticDescriptor StringJoinToArrayRule = new( 14 | "CI0003", 15 | Resources.CI0003_Title, 16 | Resources.CI0003_Title, 17 | Categories.Performance, 18 | DiagnosticSeverity.Warning, 19 | true 20 | ); 21 | 22 | public override ImmutableArray SupportedDiagnostics => 23 | ImmutableArray.Create(StringJoinToArrayRule); 24 | 25 | public override void Initialize(AnalysisContext context) 26 | { 27 | context.EnableConcurrentExecution(); 28 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); 29 | 30 | context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression); 31 | } 32 | 33 | private static void Analyze(SyntaxNodeAnalysisContext context) 34 | { 35 | var invocationExpression = (InvocationExpressionSyntax) context.Node; 36 | 37 | if (invocationExpression.Expression is MemberAccessExpressionSyntax 38 | { 39 | Expression: PredefinedTypeSyntax 40 | } memberAccessExpression && memberAccessExpression.Name.ToString() == nameof(string.Join) && 41 | invocationExpression.ArgumentList.Arguments.ElementAtOrDefault(1)?.Expression is 42 | InvocationExpressionSyntax identifier) 43 | if (ExpressionExtensions.IsRedundantMethod(context, identifier)) 44 | context.ReportDiagnostic(Diagnostic.Create(StringJoinToArrayRule, identifier.GetLocation(), 45 | identifier.ToString())); 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /Collections.Analyzer/Diagnostics/StringExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Microsoft.CodeAnalysis; 5 | using Microsoft.CodeAnalysis.CSharp.Syntax; 6 | using Microsoft.CodeAnalysis.Diagnostics; 7 | 8 | namespace Collections.Analyzer.Diagnostics 9 | { 10 | internal static class StringExtensions 11 | { 12 | public static bool ToCharArrayCalled(IMethodSymbol methodSymbol) 13 | { 14 | return methodSymbol.ContainingType.OriginalDefinition.Name == nameof(String) 15 | && methodSymbol.Name == nameof(string.ToCharArray); 16 | } 17 | 18 | public static bool IsLinqMethodCalledOnString( 19 | SyntaxNodeAnalysisContext context, 20 | InvocationExpressionSyntax invocationExpression, 21 | IMethodSymbol methodSymbol, 22 | IReadOnlyCollection methods) 23 | { 24 | if (invocationExpression.Expression is MemberAccessExpressionSyntax 25 | { 26 | Expression: IdentifierNameSyntax identifier 27 | } 28 | && methods.Contains(methodSymbol.Name)) 29 | if (context.SemanticModel.GetTypeInfo(identifier).Type?.Name == nameof(String)) 30 | return true; 31 | 32 | return false; 33 | } 34 | 35 | public static bool IsLinqMethodCalledOnMethod( 36 | SyntaxNodeAnalysisContext context, 37 | InvocationExpressionSyntax invocationExpression, 38 | IMethodSymbol methodSymbol, 39 | IReadOnlyCollection methods) 40 | { 41 | if (invocationExpression.Expression is MemberAccessExpressionSyntax 42 | { 43 | Expression: InvocationExpressionSyntax invocationExpressionSyntax 44 | } 45 | && methods.Contains(methodSymbol.Name)) 46 | if (context.SemanticModel.GetSymbolInfo(invocationExpressionSyntax).Symbol is IMethodSymbol ms 47 | && ms.ReturnType.Name == nameof(String)) 48 | return true; 49 | 50 | return false; 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /Collections.Analyzer/Diagnostics/CI0003/AssignEnumerableDiagnostic.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Immutable; 3 | using Microsoft.CodeAnalysis; 4 | using Microsoft.CodeAnalysis.CSharp; 5 | using Microsoft.CodeAnalysis.CSharp.Syntax; 6 | using Microsoft.CodeAnalysis.Diagnostics; 7 | 8 | namespace Collections.Analyzer.Diagnostics.CI0003 9 | { 10 | [DiagnosticAnalyzer(LanguageNames.CSharp)] 11 | public sealed class AssignEnumerableDiagnostic : DiagnosticAnalyzer 12 | { 13 | internal static readonly DiagnosticDescriptor AssignEnumerableRule = new( 14 | "CI0003", 15 | Resources.CI0003_Title, 16 | Resources.CI0003_Title, 17 | Categories.Performance, 18 | DiagnosticSeverity.Warning, 19 | true 20 | ); 21 | 22 | public override ImmutableArray SupportedDiagnostics => 23 | ImmutableArray.Create(AssignEnumerableRule); 24 | 25 | public override void Initialize(AnalysisContext context) 26 | { 27 | context.EnableConcurrentExecution(); 28 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); 29 | 30 | context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.VariableDeclaration); 31 | } 32 | 33 | private static void Analyze(SyntaxNodeAnalysisContext context) 34 | { 35 | var declarationExpression = (VariableDeclarationSyntax) context.Node; 36 | 37 | foreach (var variable in declarationExpression.Variables) 38 | { 39 | if (context.SemanticModel.GetDeclaredSymbol(variable) is ILocalSymbol localSymbol && 40 | localSymbol.Type.Name == nameof(IEnumerable) 41 | && variable.Initializer?.Value is InvocationExpressionSyntax invocationExpression && 42 | ExpressionExtensions.IsRedundantMethod(context, invocationExpression)) 43 | { 44 | context.ReportDiagnostic(Diagnostic.Create(AssignEnumerableRule, invocationExpression.GetLocation(), 45 | invocationExpression.ToString())); 46 | } 47 | } 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /Collections.Analyzer/Collections.Analyzer.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | netstandard2.0 4 | 10 5 | false 6 | true 7 | 0.2.13 8 | Collections.Analyzer 9 | Rogatnev Sergey 10 | Collections.Analyzer is a set of roslyn-based diagnostics for C#-projects that detect potential problems with operating different collections. 11 | https://github.com/Backs/Collections.Analyzer 12 | https://github.com/Backs/Collections.Analyzer/blob/master/LICENSE 13 | https://github.com/Backs/Collections.Analyzer 14 | enable 15 | README.md 16 | true 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | ResXFileCodeGenerator 33 | Resources.Designer.cs 34 | 35 | 36 | 37 | 38 | True 39 | True 40 | Resources.resx 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Tests/EnumerableTests/RedundantEnumerableToArrayConversionTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0003; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.EnumerableTests; 9 | 10 | public class RedundantEnumerableToArrayConversionTests : CSharpCodeFixTest< 11 | EnumerableToArrayOnReturnDiagnostic, 12 | RemoveRedundantMethodCallCodeFix, DefaultVerifier> 13 | { 14 | [Test] 15 | public Task EnumerableMethodToArrayTest() 16 | { 17 | var code = ResourceReader.ReadFromFile("EnumerableMethodToArray.txt"); 18 | 19 | return RedundantEnumerableToArrayConversionVerifier 20 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0003").WithSpan(12, 20, 12, 34)); 21 | } 22 | 23 | [Test] 24 | public Task AsyncEnumerableMethodToArrayTest() 25 | { 26 | var code = ResourceReader.ReadFromFile("AsyncEnumerableMethodToArray.txt"); 27 | 28 | return RedundantEnumerableToArrayConversionVerifier 29 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0003").WithSpan(15, 20, 15, 34)); 30 | } 31 | 32 | [Test] 33 | public Task AsyncValueTaskEnumerableMethodToArrayTest() 34 | { 35 | var code = ResourceReader.ReadFromFile("AsyncEnumerableMethodToArray2.txt"); 36 | 37 | return RedundantEnumerableToArrayConversionVerifier 38 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0003").WithSpan(13, 20, 13, 34)); 39 | } 40 | 41 | [Test] 42 | public Task EnumerablePropertyToArrayTest() 43 | { 44 | var code = ResourceReader.ReadFromFile("EnumerablePropertyToArray.txt"); 45 | 46 | return RedundantEnumerableToArrayConversionVerifier 47 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0003").WithSpan(11, 20, 11, 33)); 48 | } 49 | 50 | [Test] 51 | public Task GetSetToArrayTest() 52 | { 53 | var code = ResourceReader.ReadFromFile("GetSetToArray.txt"); 54 | 55 | return RedundantEnumerableToArrayConversionVerifier 56 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0003").WithSpan(10, 20, 10, 38)); 57 | } 58 | } -------------------------------------------------------------------------------- /Collections.Analyzer.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Examples", "Examples\Examples.csproj", "{E16581B0-8179-464E-B74E-539460260F44}" 4 | EndProject 5 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Collections.Analyzer", "Collections.Analyzer\Collections.Analyzer.csproj", "{717B3028-5A42-4AE2-87E8-5476EDF74FED}" 6 | EndProject 7 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Tests\Tests.csproj", "{AF0BC354-7942-47C1-AD4F-FC10D1B52962}" 8 | EndProject 9 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Benchmarks", "Benchmarks\Benchmarks.csproj", "{A468B48A-6A78-4A93-859D-57DE1A563C94}" 10 | EndProject 11 | Global 12 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 13 | Debug|Any CPU = Debug|Any CPU 14 | Release|Any CPU = Release|Any CPU 15 | EndGlobalSection 16 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 17 | {E16581B0-8179-464E-B74E-539460260F44}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 18 | {E16581B0-8179-464E-B74E-539460260F44}.Debug|Any CPU.Build.0 = Debug|Any CPU 19 | {E16581B0-8179-464E-B74E-539460260F44}.Release|Any CPU.ActiveCfg = Release|Any CPU 20 | {E16581B0-8179-464E-B74E-539460260F44}.Release|Any CPU.Build.0 = Release|Any CPU 21 | {717B3028-5A42-4AE2-87E8-5476EDF74FED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 22 | {717B3028-5A42-4AE2-87E8-5476EDF74FED}.Debug|Any CPU.Build.0 = Debug|Any CPU 23 | {717B3028-5A42-4AE2-87E8-5476EDF74FED}.Release|Any CPU.ActiveCfg = Release|Any CPU 24 | {717B3028-5A42-4AE2-87E8-5476EDF74FED}.Release|Any CPU.Build.0 = Release|Any CPU 25 | {AF0BC354-7942-47C1-AD4F-FC10D1B52962}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 26 | {AF0BC354-7942-47C1-AD4F-FC10D1B52962}.Debug|Any CPU.Build.0 = Debug|Any CPU 27 | {AF0BC354-7942-47C1-AD4F-FC10D1B52962}.Release|Any CPU.ActiveCfg = Release|Any CPU 28 | {AF0BC354-7942-47C1-AD4F-FC10D1B52962}.Release|Any CPU.Build.0 = Release|Any CPU 29 | {A468B48A-6A78-4A93-859D-57DE1A563C94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 30 | {A468B48A-6A78-4A93-859D-57DE1A563C94}.Debug|Any CPU.Build.0 = Debug|Any CPU 31 | {A468B48A-6A78-4A93-859D-57DE1A563C94}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 | {A468B48A-6A78-4A93-859D-57DE1A563C94}.Release|Any CPU.Build.0 = Release|Any CPU 33 | EndGlobalSection 34 | EndGlobal 35 | -------------------------------------------------------------------------------- /Benchmarks/ConcurrentCollectionsBenchmark.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Linq; 3 | using BenchmarkDotNet.Attributes; 4 | using BenchmarkDotNet.Jobs; 5 | 6 | namespace Benchmarks 7 | { 8 | [ShortRunJob(RuntimeMoniker.Net48)] 9 | [ShortRunJob(RuntimeMoniker.Net60)] 10 | [ShortRunJob(RuntimeMoniker.Net80)] 11 | [MemoryDiagnoser] 12 | public class ConcurrentCollectionsBenchmark 13 | { 14 | [Params(10000)] 15 | public int N { get; set; } 16 | 17 | private ConcurrentBag bag = new ConcurrentBag(); 18 | private ConcurrentDictionary dictionary = new ConcurrentDictionary(); 19 | private ConcurrentQueue queue = new ConcurrentQueue(); 20 | private ConcurrentStack stack = new ConcurrentStack(); 21 | 22 | [GlobalSetup] 23 | public void SetUp() 24 | { 25 | for (int i = 0; i < N; i++) 26 | { 27 | bag.Add(i); 28 | dictionary.TryAdd(i, i.ToString()); 29 | queue.Enqueue(i); 30 | stack.Push(i); 31 | } 32 | } 33 | 34 | [Benchmark] 35 | public bool ConcurrentBagAny() 36 | { 37 | return bag.Any(); 38 | } 39 | 40 | [Benchmark] 41 | public bool ConcurrentBagIsEmpty() 42 | { 43 | return !bag.IsEmpty; 44 | } 45 | 46 | [Benchmark] 47 | public bool ConcurrentDictionaryAny() 48 | { 49 | return dictionary.Any(); 50 | } 51 | 52 | [Benchmark] 53 | public bool ConcurrentDictionaryIsEmpty() 54 | { 55 | return !dictionary.IsEmpty; 56 | } 57 | 58 | [Benchmark] 59 | public bool ConcurrentQueueAny() 60 | { 61 | return queue.Any(); 62 | } 63 | 64 | [Benchmark] 65 | public bool ConcurrentQueueIsEmpty() 66 | { 67 | return !queue.IsEmpty; 68 | } 69 | 70 | [Benchmark] 71 | public bool ConcurrentStackAny() 72 | { 73 | return stack.Any(); 74 | } 75 | 76 | [Benchmark] 77 | public bool ConcurrentStackIsEmpty() 78 | { 79 | return !stack.IsEmpty; 80 | } 81 | } 82 | } -------------------------------------------------------------------------------- /Collections.Analyzer/Diagnostics/CI0005/ToArrayLengthDiagnostic.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Immutable; 4 | using System.Linq; 5 | using Microsoft.CodeAnalysis; 6 | using Microsoft.CodeAnalysis.CSharp; 7 | using Microsoft.CodeAnalysis.CSharp.Syntax; 8 | using Microsoft.CodeAnalysis.Diagnostics; 9 | 10 | namespace Collections.Analyzer.Diagnostics.CI0005 11 | { 12 | [DiagnosticAnalyzer(LanguageNames.CSharp)] 13 | public sealed class ToArrayLengthDiagnostic : DiagnosticAnalyzer 14 | { 15 | internal static readonly DiagnosticDescriptor RedundantToArrayLengthRule = new( 16 | "CI0005", 17 | Resources.CI0005_Title, 18 | Resources.CI0005_Title, 19 | Categories.Performance, 20 | DiagnosticSeverity.Warning, 21 | true 22 | ); 23 | 24 | public override ImmutableArray SupportedDiagnostics => 25 | ImmutableArray.Create(RedundantToArrayLengthRule); 26 | 27 | public override void Initialize(AnalysisContext context) 28 | { 29 | context.EnableConcurrentExecution(); 30 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); 31 | 32 | context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression); 33 | } 34 | 35 | private static void Analyze(SyntaxNodeAnalysisContext context) 36 | { 37 | var invocationExpression = (InvocationExpressionSyntax) context.Node; 38 | 39 | if (context.SemanticModel.GetSymbolInfo(invocationExpression).Symbol is not IMethodSymbol redundantMethod) 40 | return; 41 | 42 | if (invocationExpression.Parent is not MemberAccessExpressionSyntax parent) return; 43 | 44 | switch (redundantMethod.Name) 45 | { 46 | case nameof(Enumerable.ToArray) when parent.Name.Identifier.ToString() == nameof(Array.Length): 47 | case nameof(Enumerable.ToList) when parent.Name.Identifier.ToString() == nameof(List.Count): 48 | context.ReportDiagnostic(Diagnostic.Create(RedundantToArrayLengthRule, 49 | invocationExpression.Parent.GetLocation(), 50 | redundantMethod.ToString())); 51 | break; 52 | } 53 | } 54 | } 55 | } -------------------------------------------------------------------------------- /Tests/StringTests/RedundantStringToArrayConversionTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0001; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.StringTests; 9 | 10 | public class RedundantStringToArrayConversionTests : CSharpCodeFixTest 12 | { 13 | [Test] 14 | public Task ForeachToArrayTest() 15 | { 16 | var code = ResourceReader.ReadFromFile("ForeachStringToArray.txt"); 17 | 18 | return RedundantStringToArrayConversionVerifier 19 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0001").WithSpan(12, 31, 12, 44)); 20 | } 21 | 22 | [Test] 23 | public Task ForeachToCharArrayTest() 24 | { 25 | var code = ResourceReader.ReadFromFile("ForeachStringToCharArray.txt"); 26 | 27 | return RedundantStringToArrayConversionVerifier 28 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0001").WithSpan(10, 31, 10, 48)); 29 | } 30 | 31 | [Test] 32 | public Task SelectToArrayTest() 33 | { 34 | var code = ResourceReader.ReadFromFile("SelectStringToArray.txt"); 35 | 36 | return RedundantStringToArrayConversionVerifier 37 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0001").WithSpan(11, 26, 11, 39)); 38 | } 39 | 40 | [Test] 41 | public Task GetStringSelectToArrayTest() 42 | { 43 | var code = ResourceReader.ReadFromFile("GetStringSelectToArray.txt"); 44 | 45 | return RedundantStringToArrayConversionVerifier 46 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0001").WithSpan(10, 26, 10, 47)); 47 | } 48 | 49 | [TestCase("ForeachStringToArrayBefore.txt", "ForeachStringToArrayAfter.txt")] 50 | [TestCase("ForeachStringToListBefore.txt", "ForeachStringToListAfter.txt")] 51 | [TestCase("ForeachStringToCharArrayBefore.txt", "ForeachStringToCharArrayAfter.txt")] 52 | [TestCase("GetStringToCharArraySelectBefore.txt", "GetStringToCharArraySelectAfter.txt")] 53 | public Task CodeFixesTest(string before, string after) 54 | { 55 | var code = ResourceReader.ReadFromFile(before); 56 | var fixedCode = ResourceReader.ReadFromFile(after); 57 | 58 | return RedundantStringToArrayConversionVerifier.VerifyCodeFixAsync(code, fixedCode); 59 | } 60 | } -------------------------------------------------------------------------------- /Collections.Analyzer/Diagnostics/CI0003/ObjectInitializerDiagnostic.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using System.Linq; 3 | using Microsoft.CodeAnalysis; 4 | using Microsoft.CodeAnalysis.CSharp; 5 | using Microsoft.CodeAnalysis.CSharp.Syntax; 6 | using Microsoft.CodeAnalysis.Diagnostics; 7 | 8 | namespace Collections.Analyzer.Diagnostics.CI0003 9 | { 10 | [DiagnosticAnalyzer(LanguageNames.CSharp)] 11 | public class ObjectInitializerDiagnostic : DiagnosticAnalyzer 12 | { 13 | internal static readonly DiagnosticDescriptor RedundantArrayToArrayRule = new( 14 | "CI0003", 15 | Resources.CI0003_Title, 16 | Resources.CI0003_Title, 17 | Categories.Performance, 18 | DiagnosticSeverity.Warning, 19 | true 20 | ); 21 | 22 | public override ImmutableArray SupportedDiagnostics => 23 | ImmutableArray.Create(RedundantArrayToArrayRule); 24 | 25 | public override void Initialize(AnalysisContext context) 26 | { 27 | context.EnableConcurrentExecution(); 28 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); 29 | 30 | context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.ObjectInitializerExpression); 31 | } 32 | 33 | private static void Analyze(SyntaxNodeAnalysisContext context) 34 | { 35 | var initializerExpressionSyntax = (InitializerExpressionSyntax) context.Node; 36 | 37 | foreach (var expression in initializerExpressionSyntax.Expressions.OfType()) 38 | { 39 | if (expression.Left is IdentifierNameSyntax && 40 | expression.Right is InvocationExpressionSyntax rightInvocationExpression && 41 | IsArrayProperty(context, rightInvocationExpression) && 42 | ExpressionExtensions.IsRedundantMethod(context, rightInvocationExpression) 43 | ) 44 | { 45 | context.ReportDiagnostic(Diagnostic.Create(RedundantArrayToArrayRule, 46 | rightInvocationExpression.GetLocation(), 47 | rightInvocationExpression.ToString())); 48 | } 49 | } 50 | } 51 | 52 | private static bool IsArrayProperty(SyntaxNodeAnalysisContext context, InvocationExpressionSyntax invocationExpression) 53 | { 54 | return invocationExpression.Expression is MemberAccessExpressionSyntax 55 | { 56 | Expression: MemberAccessExpressionSyntax memberAccessExpression 57 | } && 58 | context.SemanticModel.GetTypeInfo(memberAccessExpression).Type?.Kind == SymbolKind.ArrayType; 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /Examples/Enumerable/ReturnArray.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | 5 | namespace Examples.Enumerable 6 | { 7 | public class ReturnArray 8 | { 9 | public static IEnumerable Method1() 10 | { 11 | IEnumerable list = new List(); 12 | 13 | list = list.Select(o => o); 14 | 15 | return list.ToArray(); 16 | } 17 | 18 | public static async Task> Method1Async() 19 | { 20 | IEnumerable list = new List(); 21 | 22 | list = list.Select(o => o); 23 | 24 | await Task.CompletedTask; 25 | 26 | return list.ToArray(); 27 | } 28 | 29 | public static IEnumerable Method2() 30 | { 31 | var list = new List(); 32 | 33 | return list.ToArray(); 34 | } 35 | 36 | public static IEnumerable Method3() 37 | { 38 | var list = new HashSet(); 39 | 40 | return list.ToList(); 41 | } 42 | 43 | public static async Task> Method3Async() 44 | { 45 | var list = new HashSet(); 46 | 47 | await Task.CompletedTask; 48 | 49 | return list.ToList(); 50 | } 51 | 52 | public static async ValueTask> Method4Async() 53 | { 54 | var list = new HashSet(); 55 | 56 | await Task.CompletedTask; 57 | 58 | return list.ToList(); 59 | } 60 | 61 | public static IEnumerable Method4() 62 | { 63 | return GetSet().ToArray(); 64 | } 65 | 66 | public static HashSet GetSet() 67 | { 68 | return new HashSet(); 69 | } 70 | 71 | public static int[] Method() 72 | { 73 | var list = new List(); 74 | 75 | return list.ToArray(); 76 | } 77 | 78 | public static IReadOnlyCollection Method5() 79 | { 80 | var list = new HashSet(); 81 | 82 | return list.ToList(); 83 | } 84 | 85 | public static IEnumerable Property1 86 | { 87 | get 88 | { 89 | var list = new HashSet(); 90 | 91 | return list.ToList(); 92 | } 93 | } 94 | 95 | public static IEnumerable Property2 96 | { 97 | get 98 | { 99 | var list = GetSet(); 100 | 101 | return list.ToList(); 102 | } 103 | } 104 | } 105 | } -------------------------------------------------------------------------------- /Collections.Analyzer/Diagnostics/CI0003/ConstructorDiagnostic.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using System.Linq; 3 | using Microsoft.CodeAnalysis; 4 | using Microsoft.CodeAnalysis.CSharp; 5 | using Microsoft.CodeAnalysis.CSharp.Syntax; 6 | using Microsoft.CodeAnalysis.Diagnostics; 7 | 8 | namespace Collections.Analyzer.Diagnostics.CI0003 9 | { 10 | [DiagnosticAnalyzer(LanguageNames.CSharp)] 11 | public class ConstructorDiagnostic : DiagnosticAnalyzer 12 | { 13 | internal static readonly DiagnosticDescriptor ConstructorRule = new( 14 | "CI0003", 15 | Resources.CI0003_Title, 16 | Resources.CI0003_Title, 17 | Categories.Performance, 18 | DiagnosticSeverity.Warning, 19 | true 20 | ); 21 | 22 | public override ImmutableArray SupportedDiagnostics => 23 | ImmutableArray.Create(ConstructorRule); 24 | 25 | public override void Initialize(AnalysisContext context) 26 | { 27 | context.EnableConcurrentExecution(); 28 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); 29 | 30 | context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.ObjectCreationExpression); 31 | } 32 | 33 | private static void Analyze(SyntaxNodeAnalysisContext context) 34 | { 35 | var objectCreationExpression = (ObjectCreationExpressionSyntax) context.Node; 36 | 37 | if (objectCreationExpression.ArgumentList?.Arguments == null) return; 38 | 39 | var constructor = context.SemanticModel.GetSymbolInfo(objectCreationExpression).Symbol as IMethodSymbol; 40 | 41 | if (constructor == null) return; 42 | 43 | var parameters = constructor 44 | .Parameters; 45 | 46 | for (var i = 0; i < objectCreationExpression.ArgumentList.Arguments.Count; i++) 47 | { 48 | var argument = objectCreationExpression.ArgumentList.Arguments[i]; 49 | if (argument.Expression is not InvocationExpressionSyntax invocationExpression) continue; 50 | 51 | if (!ExpressionExtensions.IsRedundantMethod(context, invocationExpression)) continue; 52 | 53 | var callerType = ExpressionExtensions.GetCallerType(context, invocationExpression); 54 | if (callerType == null) 55 | continue; 56 | 57 | var parameter = parameters[i]; 58 | 59 | if (SymbolEqualityComparer.Default.Equals(callerType, parameter.Type) || 60 | callerType.AllInterfaces.Contains(parameter.Type)) 61 | { 62 | context.ReportDiagnostic(Diagnostic.Create(ConstructorRule, invocationExpression.GetLocation(), 63 | invocationExpression.ToString())); 64 | } 65 | } 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /Collections.Analyzer/CodeFixes/ReplaceWithCountCodeFix.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using System.Composition; 3 | using System.Linq; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using Collections.Analyzer.Diagnostics.CI0005; 7 | using Microsoft.CodeAnalysis; 8 | using Microsoft.CodeAnalysis.CodeActions; 9 | using Microsoft.CodeAnalysis.CodeFixes; 10 | using Microsoft.CodeAnalysis.CSharp; 11 | using Microsoft.CodeAnalysis.CSharp.Syntax; 12 | using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; 13 | 14 | namespace Collections.Analyzer.CodeFixes 15 | { 16 | [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(ReplaceWithCountCodeFix))] 17 | [Shared] 18 | public class ReplaceWithCountCodeFix : CodeFixProvider 19 | { 20 | public override ImmutableArray FixableDiagnosticIds => ImmutableArray.Create( 21 | ToArrayLengthDiagnostic.RedundantToArrayLengthRule.Id); 22 | 23 | public override async Task RegisterCodeFixesAsync(CodeFixContext context) 24 | { 25 | var root = await context.Document.GetSyntaxRootAsync(); 26 | var diagnostic = context.Diagnostics.First(); 27 | 28 | var syntaxNode = root!.FindNode(context.Span) as MemberAccessExpressionSyntax; 29 | if (syntaxNode?.Expression is not InvocationExpressionSyntax invocationExpressionSyntax) return; 30 | 31 | var title = Resources.ReplaceWithCountCall; 32 | 33 | context.RegisterCodeFix( 34 | CodeAction.Create( 35 | title, 36 | token => FixAsync(context.Document, invocationExpressionSyntax, token), 37 | title 38 | ), 39 | diagnostic 40 | ); 41 | } 42 | 43 | private static async Task FixAsync(Document document, InvocationExpressionSyntax originalExpression, 44 | CancellationToken cancellationToken) 45 | { 46 | var internalExpression = (originalExpression.Expression as MemberAccessExpressionSyntax)?.Expression; 47 | 48 | if (internalExpression == null || originalExpression.Parent == null) return document; 49 | 50 | var newExpression = InvocationExpression( 51 | MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, 52 | internalExpression, 53 | IdentifierName(nameof(Enumerable.Count))), originalExpression.ArgumentList).NormalizeWhitespace(); 54 | 55 | var oldRoot = await document.GetSyntaxRootAsync(cancellationToken); 56 | var newRoot = oldRoot!.ReplaceNode(originalExpression.Parent, newExpression); 57 | 58 | return document.WithSyntaxRoot(newRoot); 59 | } 60 | 61 | public override FixAllProvider GetFixAllProvider() 62 | { 63 | return WellKnownFixAllProviders.BatchFixer; 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /Collections.Analyzer/Diagnostics/CI0002/ArrayToArrayDiagnostic.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using System.Linq; 3 | using Microsoft.CodeAnalysis; 4 | using Microsoft.CodeAnalysis.CSharp; 5 | using Microsoft.CodeAnalysis.CSharp.Syntax; 6 | using Microsoft.CodeAnalysis.Diagnostics; 7 | 8 | namespace Collections.Analyzer.Diagnostics.CI0002 9 | { 10 | [DiagnosticAnalyzer(LanguageNames.CSharp)] 11 | public sealed class ArrayToArrayDiagnostic : DiagnosticAnalyzer 12 | { 13 | internal static readonly DiagnosticDescriptor RedundantArrayToArrayRule = new( 14 | "CI0002", 15 | Resources.CI0002_Title, 16 | Resources.CI0002_Title, 17 | Categories.Performance, 18 | DiagnosticSeverity.Warning, 19 | true 20 | ); 21 | 22 | public override ImmutableArray SupportedDiagnostics => 23 | ImmutableArray.Create(RedundantArrayToArrayRule); 24 | 25 | public override void Initialize(AnalysisContext context) 26 | { 27 | context.EnableConcurrentExecution(); 28 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); 29 | 30 | context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression); 31 | } 32 | 33 | private static void Analyze(SyntaxNodeAnalysisContext context) 34 | { 35 | var invocationExpression = (InvocationExpressionSyntax) context.Node; 36 | 37 | var redundantMethod = context.SemanticModel.GetSymbolInfo(invocationExpression).Symbol as IMethodSymbol; 38 | if (redundantMethod is not {Name: nameof(Enumerable.ToArray)} 39 | || redundantMethod.ContainingType.Name != nameof(Enumerable)) 40 | return; 41 | 42 | if (invocationExpression.Expression is MemberAccessExpressionSyntax 43 | { 44 | Expression: IdentifierNameSyntax identifier 45 | } 46 | && context.SemanticModel.GetTypeInfo(identifier).Type?.TypeKind == TypeKind.Array) 47 | context.ReportDiagnostic(Diagnostic.Create(RedundantArrayToArrayRule, 48 | invocationExpression.GetLocation(), 49 | redundantMethod.ToString())); 50 | else if (invocationExpression.Expression is MemberAccessExpressionSyntax 51 | { 52 | Expression: InvocationExpressionSyntax invocationExpressionSyntax 53 | } 54 | && context.SemanticModel.GetSymbolInfo(invocationExpressionSyntax).Symbol is IMethodSymbol ms 55 | && ms.ReturnType.TypeKind == TypeKind.Array) 56 | context.ReportDiagnostic(Diagnostic.Create(RedundantArrayToArrayRule, 57 | invocationExpression.GetLocation(), 58 | redundantMethod.ToString())); 59 | } 60 | } 61 | } -------------------------------------------------------------------------------- /Collections.Analyzer/CodeFixes/AddToCharArrayCodeFix.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using System.Composition; 3 | using System.Linq; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using Collections.Analyzer.Diagnostics.CI0004; 7 | using Microsoft.CodeAnalysis; 8 | using Microsoft.CodeAnalysis.CodeActions; 9 | using Microsoft.CodeAnalysis.CodeFixes; 10 | using Microsoft.CodeAnalysis.CSharp; 11 | using Microsoft.CodeAnalysis.CSharp.Syntax; 12 | 13 | namespace Collections.Analyzer.CodeFixes 14 | { 15 | using static SyntaxFactory; 16 | 17 | [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AddToCharArrayCodeFix))] 18 | [Shared] 19 | public class AddToCharArrayCodeFix : CodeFixProvider 20 | { 21 | public override ImmutableArray FixableDiagnosticIds => ImmutableArray.Create( 22 | ListFromStringDiagnostic.ListFromStringRule.Id); 23 | 24 | public override async Task RegisterCodeFixesAsync(CodeFixContext context) 25 | { 26 | var root = await context.Document.GetSyntaxRootAsync(); 27 | var diagnostic = context.Diagnostics.First(); 28 | 29 | var arg = root!.FindNode(context.Span) as ArgumentSyntax; 30 | 31 | var title = arg?.Expression is IdentifierNameSyntax 32 | ? Resources.AddToCharArray 33 | : Resources.ReplaceWithToCharArray; 34 | 35 | context.RegisterCodeFix( 36 | CodeAction.Create( 37 | title, 38 | token => FixAsync(context.Document, arg?.Expression, token), 39 | title 40 | ), 41 | diagnostic 42 | ); 43 | } 44 | 45 | private static async Task FixAsync(Document document, ExpressionSyntax? originalExpression, 46 | CancellationToken cancellationToken) 47 | { 48 | var identifier = originalExpression as IdentifierNameSyntax; 49 | 50 | if (identifier == null) 51 | identifier = 52 | ((originalExpression as InvocationExpressionSyntax)?.Expression as MemberAccessExpressionSyntax) 53 | ?.Expression as IdentifierNameSyntax; 54 | 55 | if (identifier == null) return document; 56 | 57 | var newExpression = InvocationExpression( 58 | MemberAccessExpression( 59 | SyntaxKind.SimpleMemberAccessExpression, 60 | IdentifierName(identifier.Identifier), 61 | IdentifierName(nameof(string.ToCharArray)))); 62 | 63 | var oldRoot = await document.GetSyntaxRootAsync(cancellationToken); 64 | var newRoot = oldRoot!.ReplaceNode(originalExpression!, newExpression); 65 | 66 | return document.WithSyntaxRoot(newRoot); 67 | } 68 | 69 | public override FixAllProvider GetFixAllProvider() 70 | { 71 | return WellKnownFixAllProviders.BatchFixer; 72 | } 73 | } 74 | } -------------------------------------------------------------------------------- /Collections.Analyzer/Diagnostics/CI0006/ListInitializerDiagnostic.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using Microsoft.CodeAnalysis; 3 | using Microsoft.CodeAnalysis.CSharp; 4 | using Microsoft.CodeAnalysis.CSharp.Syntax; 5 | using Microsoft.CodeAnalysis.Diagnostics; 6 | 7 | namespace Collections.Analyzer.Diagnostics.CI0006 8 | { 9 | [DiagnosticAnalyzer(LanguageNames.CSharp)] 10 | public sealed class ListInitializerDiagnostic : DiagnosticAnalyzer 11 | { 12 | internal static readonly DiagnosticDescriptor InitializeListWithCapacityRule = new( 13 | "CI0006", 14 | Resources.CI0006_Title, 15 | "{0}", 16 | Categories.Performance, 17 | DiagnosticSeverity.Warning, 18 | true 19 | ); 20 | 21 | public override ImmutableArray SupportedDiagnostics => 22 | ImmutableArray.Create(InitializeListWithCapacityRule); 23 | 24 | public override void Initialize(AnalysisContext context) 25 | { 26 | context.EnableConcurrentExecution(); 27 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); 28 | 29 | context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.ObjectCreationExpression); 30 | } 31 | 32 | private static void Analyze(SyntaxNodeAnalysisContext context) 33 | { 34 | var objectCreationExpression = (ObjectCreationExpressionSyntax)context.Node; 35 | 36 | if (objectCreationExpression.Type is GenericNameSyntax genericName 37 | && genericName.Identifier.ToString() == "List" 38 | && objectCreationExpression.Initializer?.Expressions.Count > 0) 39 | { 40 | if (objectCreationExpression.ArgumentList == null || 41 | objectCreationExpression.ArgumentList?.Arguments.Count == 0) 42 | { 43 | context.ReportDiagnostic(Diagnostic.Create(InitializeListWithCapacityRule, 44 | objectCreationExpression.GetLocation(), Resources.CI0006_Title)); 45 | } 46 | else if (LessCapacity(context, objectCreationExpression)) 47 | { 48 | context.ReportDiagnostic(Diagnostic.Create(InitializeListWithCapacityRule, 49 | objectCreationExpression.GetLocation(), Resources.NotEnoughCapacity)); 50 | } 51 | } 52 | } 53 | 54 | private static bool LessCapacity(SyntaxNodeAnalysisContext context, 55 | BaseObjectCreationExpressionSyntax objectCreationExpression) 56 | { 57 | var argument = objectCreationExpression.ArgumentList!.Arguments.First(); 58 | if (argument.Expression is not LiteralExpressionSyntax) return false; 59 | 60 | var capacity = context.SemanticModel.GetConstantValue(argument.Expression).Value as int?; 61 | 62 | return capacity < objectCreationExpression.Initializer?.Expressions.Count; 63 | } 64 | } 65 | } -------------------------------------------------------------------------------- /Collections.Analyzer/CodeFixes/ReplaceAnyWithIsEmptyCodeFix.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Collections.Immutable; 3 | using System.Composition; 4 | using System.Linq; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Collections.Analyzer.Diagnostics.CI0007; 8 | using Microsoft.CodeAnalysis; 9 | using Microsoft.CodeAnalysis.CodeActions; 10 | using Microsoft.CodeAnalysis.CodeFixes; 11 | using Microsoft.CodeAnalysis.CSharp; 12 | using Microsoft.CodeAnalysis.CSharp.Syntax; 13 | 14 | namespace Collections.Analyzer.CodeFixes; 15 | 16 | using static SyntaxFactory; 17 | 18 | [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(ReplaceAnyWithIsEmptyCodeFix))] 19 | [Shared] 20 | public class ReplaceAnyWithIsEmptyCodeFix : CodeFixProvider 21 | { 22 | public override ImmutableArray FixableDiagnosticIds => ImmutableArray.Create( 23 | ConcurrentCollectionIsEmptyDiagnostic.ReplaceAnyWithIsEmptyRule.Id); 24 | 25 | public override async Task RegisterCodeFixesAsync(CodeFixContext context) 26 | { 27 | var root = await context.Document.GetSyntaxRootAsync(); 28 | var diagnostic = context.Diagnostics.First(); 29 | 30 | var memberAccessExpressionSyntax = root!.FindNode(context.Span) as MemberAccessExpressionSyntax; 31 | if (memberAccessExpressionSyntax == null) 32 | return; 33 | 34 | var title = Resources.ReplaceWithIsEmpty; 35 | 36 | context.RegisterCodeFix( 37 | CodeAction.Create( 38 | title, 39 | token => FixAsync(context.Document, memberAccessExpressionSyntax, token), 40 | title 41 | ), 42 | diagnostic 43 | ); 44 | } 45 | 46 | private static async Task FixAsync(Document document, MemberAccessExpressionSyntax originalExpression, 47 | CancellationToken cancellationToken) 48 | { 49 | ExpressionSyntax newExpression = MemberAccessExpression( 50 | SyntaxKind.SimpleMemberAccessExpression, 51 | originalExpression.Expression, 52 | IdentifierName(nameof(ConcurrentDictionary.IsEmpty))); 53 | 54 | var expressionParent = originalExpression.Parent; 55 | 56 | if (expressionParent?.Parent is PrefixUnaryExpressionSyntax 57 | { 58 | RawKind: (int)SyntaxKind.LogicalNotExpression 59 | }) 60 | { 61 | expressionParent = expressionParent.Parent; 62 | } 63 | else 64 | { 65 | newExpression = PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, newExpression); 66 | } 67 | 68 | newExpression.NormalizeWhitespace(); 69 | 70 | var oldRoot = await document.GetSyntaxRootAsync(cancellationToken); 71 | var newRoot = oldRoot!.ReplaceNode(expressionParent, newExpression); 72 | 73 | return document.WithSyntaxRoot(newRoot); 74 | } 75 | 76 | public override FixAllProvider GetFixAllProvider() 77 | { 78 | return WellKnownFixAllProviders.BatchFixer; 79 | } 80 | } -------------------------------------------------------------------------------- /Collections.Analyzer/CodeFixes/SetListCapacityCodeFix.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using System.Composition; 3 | using System.Linq; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using Collections.Analyzer.Diagnostics.CI0006; 7 | using Microsoft.CodeAnalysis; 8 | using Microsoft.CodeAnalysis.CodeActions; 9 | using Microsoft.CodeAnalysis.CodeFixes; 10 | using Microsoft.CodeAnalysis.CSharp; 11 | using Microsoft.CodeAnalysis.CSharp.Syntax; 12 | 13 | namespace Collections.Analyzer.CodeFixes 14 | { 15 | using static SyntaxFactory; 16 | 17 | [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(SetListCapacityCodeFix))] 18 | [Shared] 19 | public class SetListCapacityCodeFix : CodeFixProvider 20 | { 21 | public override ImmutableArray FixableDiagnosticIds => ImmutableArray.Create( 22 | ListInitializerDiagnostic.InitializeListWithCapacityRule.Id); 23 | 24 | public override async Task RegisterCodeFixesAsync(CodeFixContext context) 25 | { 26 | var root = await context.Document.GetSyntaxRootAsync(); 27 | var diagnostic = context.Diagnostics.First(); 28 | var objectCreationExpression = (ObjectCreationExpressionSyntax)root!.FindNode(context.Span); 29 | 30 | context.RegisterCodeFix( 31 | CodeAction.Create( 32 | Resources.SetActualCapacity, 33 | token => FixAsync(context.Document, objectCreationExpression, token), 34 | "Set capacity" 35 | ), 36 | diagnostic 37 | ); 38 | } 39 | 40 | private static async Task FixAsync(Document document, 41 | ObjectCreationExpressionSyntax objectCreationExpression, 42 | CancellationToken cancellationToken) 43 | { 44 | var oldRoot = await document.GetSyntaxRootAsync(cancellationToken); 45 | var capacity = objectCreationExpression.Initializer!.Expressions.Count; 46 | var genericNameSyntax = (GenericNameSyntax) objectCreationExpression.Type; 47 | 48 | var newObject = ObjectCreationExpression( 49 | GenericName(genericNameSyntax.Identifier) 50 | .WithTypeArgumentList(genericNameSyntax.TypeArgumentList)) 51 | .WithArgumentList( 52 | ArgumentList( 53 | SingletonSeparatedList( 54 | Argument( 55 | LiteralExpression( 56 | SyntaxKind.NumericLiteralExpression, 57 | Literal(capacity)))))) 58 | .WithInitializer(objectCreationExpression.Initializer); 59 | 60 | var newRoot = oldRoot!.ReplaceNode(objectCreationExpression, newObject); 61 | 62 | return document.WithSyntaxRoot(newRoot); 63 | } 64 | 65 | 66 | public override FixAllProvider GetFixAllProvider() 67 | { 68 | return WellKnownFixAllProviders.BatchFixer; 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /Collections.Analyzer/Diagnostics/CI0007/ConcurrentCollectionIsEmptyDiagnostic.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.Immutable; 3 | using System.Linq; 4 | using Microsoft.CodeAnalysis; 5 | using Microsoft.CodeAnalysis.CSharp; 6 | using Microsoft.CodeAnalysis.CSharp.Syntax; 7 | using Microsoft.CodeAnalysis.Diagnostics; 8 | 9 | namespace Collections.Analyzer.Diagnostics.CI0007; 10 | 11 | [DiagnosticAnalyzer(LanguageNames.CSharp)] 12 | public class ConcurrentCollectionIsEmptyDiagnostic : DiagnosticAnalyzer 13 | { 14 | internal static readonly DiagnosticDescriptor ReplaceAnyWithIsEmptyRule = new( 15 | "CI0007", 16 | Resources.CI0007_Title, 17 | Resources.CI0007_Title, 18 | Categories.Performance, 19 | DiagnosticSeverity.Warning, 20 | true 21 | ); 22 | 23 | public override ImmutableArray SupportedDiagnostics => 24 | ImmutableArray.Create(ReplaceAnyWithIsEmptyRule); 25 | 26 | private static readonly HashSet ConcurrentTypes = new(new[] 27 | { 28 | "ConcurrentDictionary", 29 | "ConcurrentBag", 30 | "ConcurrentQueue", 31 | "ConcurrentStack" 32 | }); 33 | 34 | public override void Initialize(AnalysisContext context) 35 | { 36 | context.EnableConcurrentExecution(); 37 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); 38 | 39 | context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression); 40 | } 41 | 42 | private static void Analyze(SyntaxNodeAnalysisContext context) 43 | { 44 | var invocationExpression = (InvocationExpressionSyntax)context.Node; 45 | 46 | var redundantMethod = context.SemanticModel.GetSymbolInfo(invocationExpression).Symbol as IMethodSymbol; 47 | if (redundantMethod is not { Name: nameof(Enumerable.Any) } 48 | || redundantMethod.ContainingType.Name != nameof(Enumerable) 49 | || redundantMethod.Parameters.Length != 0) 50 | return; 51 | 52 | if (invocationExpression.Expression is MemberAccessExpressionSyntax 53 | { 54 | Expression: IdentifierNameSyntax identifier 55 | } && context.SemanticModel.GetTypeInfo(identifier).Type != null 56 | && ConcurrentTypes.Contains(context.SemanticModel.GetTypeInfo(identifier).Type.Name) 57 | ) 58 | { 59 | context.ReportDiagnostic(Diagnostic.Create(ReplaceAnyWithIsEmptyRule, 60 | invocationExpression.Expression.GetLocation(), 61 | redundantMethod.ToString())); 62 | } 63 | else if (invocationExpression.Expression is MemberAccessExpressionSyntax 64 | { 65 | Expression: InvocationExpressionSyntax invocationExpressionSyntax 66 | } 67 | && context.SemanticModel.GetSymbolInfo(invocationExpressionSyntax).Symbol is IMethodSymbol ms 68 | && ConcurrentTypes.Contains(ms.ReturnType.Name)) 69 | { 70 | context.ReportDiagnostic(Diagnostic.Create(ReplaceAnyWithIsEmptyRule, 71 | invocationExpression.Expression.GetLocation(), 72 | redundantMethod.ToString())); 73 | } 74 | } 75 | } -------------------------------------------------------------------------------- /Documentation/CI0003.md: -------------------------------------------------------------------------------- 1 | # CI0003: Redundant enumerable conversion 2 | Redundant `ToArray` or `ToList` method call on types that implements `IEnumerable` interface. 3 | 4 | ## Examples 5 | 6 | ### Return `IEnumerable` type 7 | ```csharp 8 | public static IEnumerable Method1() 9 | { 10 | var list = new List(); 11 | 12 | return list.ToArray(); 13 | } 14 | ``` 15 | 16 | ```csharp 17 | public static IEnumerable Method2() 18 | { 19 | var list = new HashSet(); 20 | 21 | return list.ToList(); 22 | } 23 | ``` 24 | 25 | ``` 26 | public static async Task> MethodAsync() 27 | { 28 | var list = new HashSet(); 29 | 30 | // ... await 31 | 32 | return list.ToList(); 33 | } 34 | ``` 35 | 36 | ``` 37 | public static IEnumerable Method() 38 | { 39 | return GetSet().ToArray(); 40 | } 41 | 42 | public static HashSet GetSet() 43 | { 44 | return new HashSet(); 45 | } 46 | ``` 47 | 48 | ``` 49 | public static IEnumerable Property 50 | { 51 | get 52 | { 53 | var list = new HashSet(); 54 | 55 | return list.ToList(); 56 | } 57 | } 58 | ``` 59 | 60 | ### Method calls 61 | ``` 62 | public static void JoinArray() 63 | { 64 | var array = new int[10]; 65 | 66 | var result = string.Join("; ", array.Where(o => o != 1).ToArray()); 67 | } 68 | ``` 69 | 70 | ``` 71 | public array void AddRange() 72 | { 73 | var list = new List(); 74 | IEnumerable array = new int[10]; 75 | 76 | list.AddRange(array.ToArray()); 77 | } 78 | ``` 79 | 80 | ### Constructor 81 | ``` 82 | public class Constructor 83 | { 84 | public void CallConstructor() 85 | { 86 | var list = System.Linq.Enumerable.Empty(); 87 | 88 | var obj = new MyClass(list.ToArray()); 89 | } 90 | 91 | private class MyClass 92 | { 93 | private readonly IEnumerable source; 94 | 95 | public MyClass(IEnumerable source) 96 | { 97 | source = source; 98 | } 99 | } 100 | } 101 | ``` 102 | 103 | ### Variable initializer 104 | ``` 105 | public class AssignEnumerable 106 | { 107 | public void Method1() 108 | { 109 | IEnumerable result = GetArray().ToArray(); 110 | } 111 | 112 | public void Method2() 113 | { 114 | var enumerable = System.Linq.Enumerable.Empty(); 115 | IEnumerable result = enumerable.ToList(); 116 | } 117 | 118 | private static IEnumerable GetArray() 119 | { 120 | return new int[10]; 121 | } 122 | } 123 | ``` 124 | 125 | ### Object initializer 126 | 127 | ``` 128 | private static void Initialize() 129 | { 130 | var value1 = new MyClass 131 | { 132 | ArrayProperty = Array.Empty(), 133 | EnumerableProperty = Array.Empty() 134 | }; 135 | 136 | var value2 = new MyClass 137 | { 138 | ArrayProperty = value1.ArrayProperty.ToArray(), 139 | EnumerableProperty = value1.EnumerableProperty.ToList() 140 | }; 141 | } 142 | 143 | private class MyClass 144 | { 145 | public int[] ArrayProperty { get; set; } 146 | public IEnumerable EnumerableProperty { get; set; } 147 | } 148 | ``` -------------------------------------------------------------------------------- /Tests/ArrayContainsToHashSetTests/ArrayContainsToHashSetTests.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Collections.Analyzer.CodeFixes; 3 | using Collections.Analyzer.Diagnostics.CI0008; 4 | using Microsoft.CodeAnalysis.CSharp.Testing; 5 | using Microsoft.CodeAnalysis.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace Tests.ArrayContainsToHashSetTests; 9 | 10 | [TestFixture] 11 | public class ArrayContainsToHashSetTests : CSharpCodeFixTest< 12 | ArrayContainsToHashSetDiagnostic, ArrayContainsToHashSetCodeFix, DefaultVerifier> 13 | { 14 | [Test] 15 | public Task LocalVariableImplicitArray_ShouldWarn() 16 | { 17 | var code = ResourceReader.ReadFromFile("ArrayContains1.txt"); 18 | 19 | return ArrayContainsVerifier 20 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0008").WithSpan(7, 13, 7, 20)); 21 | } 22 | 23 | [Test] 24 | public Task FieldExplicitArray_ShouldWarn() 25 | { 26 | var code = ResourceReader.ReadFromFile("ArrayContains2.txt"); 27 | 28 | return ArrayContainsVerifier 29 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0008").WithSpan(5, 28, 5, 34)); 30 | } 31 | 32 | [Test] 33 | public Task FieldCollectionInitializer_ShouldWarn() 34 | { 35 | var code = ResourceReader.ReadFromFile("ArrayContains3.txt"); 36 | 37 | return ArrayContainsVerifier 38 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0008").WithSpan(5, 28, 5, 34)); 39 | } 40 | 41 | [Test] 42 | public Task PropertyImplicitArray_ShouldWarn() 43 | { 44 | var code = ResourceReader.ReadFromFile("ArrayContains4.txt"); 45 | 46 | return ArrayContainsVerifier 47 | .VerifyAnalyzerAsync(code, DiagnosticResult.CompilerWarning("CI0008").WithSpan(5, 18, 5, 23)); 48 | } 49 | 50 | [Test] 51 | public Task ArrayWithIndexAccess_ShouldNotWarn() 52 | { 53 | var code = ResourceReader.ReadFromFile("ArrayContains5.txt"); 54 | 55 | return ArrayContainsVerifier 56 | .VerifyAnalyzerAsync(code, DiagnosticResult.EmptyDiagnosticResults); 57 | } 58 | 59 | [Test] 60 | public Task ArrayWithModification_ShouldNotWarn() 61 | { 62 | var code = ResourceReader.ReadFromFile("ArrayContains6.txt"); 63 | 64 | return ArrayContainsVerifier 65 | .VerifyAnalyzerAsync(code, DiagnosticResult.EmptyDiagnosticResults); 66 | } 67 | 68 | [Test] 69 | public Task ArrayWithoutContains_ShouldNotWarn() 70 | { 71 | var code = ResourceReader.ReadFromFile("ArrayContains7.txt"); 72 | 73 | return ArrayContainsVerifier 74 | .VerifyAnalyzerAsync(code, DiagnosticResult.EmptyDiagnosticResults); 75 | } 76 | 77 | [Test] 78 | [TestCase("ArrayContainsBefore1.txt", "ArrayContainsAfter1.txt")] 79 | [TestCase("ArrayContainsBefore2.txt", "ArrayContainsAfter2.txt")] 80 | [TestCase("ArrayContainsBefore3.txt", "ArrayContainsAfter3.txt", Ignore = "Different syntax tree in result")] 81 | [TestCase("ArrayContainsBefore4.txt", "ArrayContainsAfter4.txt")] 82 | public Task CodeFixesTest(string before, string after) 83 | { 84 | var code = ResourceReader.ReadFromFile(before); 85 | var fixedCode = ResourceReader.ReadFromFile(after); 86 | 87 | return ArrayContainsVerifier.VerifyCodeFixAsync(code, fixedCode); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /Collections.Analyzer/Resources.ru.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | text/microsoft-resx 4 | 5 | 6 | 1.3 7 | 8 | 9 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, 10 | PublicKeyToken=b77a5c561934e089 11 | 12 | 13 | 14 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, 15 | PublicKeyToken=b77a5c561934e089 16 | 17 | 18 | 19 | Избыточное преобразование строки 20 | 21 | 22 | Удалить вызов метода {0} 23 | 24 | 25 | Избыточное преобразование массива 26 | 27 | 28 | Избыточное преобразование типа 29 | 30 | 31 | Не оптимальное использование конструктора List<char> 32 | 33 | 34 | Добавить вызов метода ToCharArray 35 | 36 | 37 | Заменить на вызов метода ToCharArray 38 | 39 | 40 | Заменить на вызов свойства Count 41 | 42 | 43 | Неоптимальный подсчет элементов коллекции 44 | 45 | 46 | Инициализация коллекции используется без указания первоначального размера 47 | 48 | 49 | Первоначальный размер коллекции не соответсвует количеству элементов при инициализации 50 | 51 | 52 | Указать первоначальный размер коллекции 53 | 54 | 55 | Вызов метода Any() блокирует коллекцию 56 | 57 | 58 | Заменить на вызов свойства IsEmpty 59 | 60 | 61 | Рассмотрите использование HashSet вместо массива для операций Contains 62 | 63 | 64 | Массив '{0}' используется с методом Contains(). Рассмотрите использование HashSet&lt;{1}&gt; для лучшей производительности 65 | 66 | 67 | HashSet<T> обеспечивает время поиска O(1) для операции Contains(), в то время как массив имеет сложность O(n) 68 | 69 | 70 | Заменить массив на HashSet 71 | 72 | -------------------------------------------------------------------------------- /Collections.Analyzer/CodeFixes/RemoveRedundantMethodCallCodeFix.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Immutable; 2 | using System.Composition; 3 | using System.Linq; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using Collections.Analyzer.Diagnostics.CI0001; 7 | using Collections.Analyzer.Diagnostics.CI0002; 8 | using Collections.Analyzer.Diagnostics.CI0003; 9 | using Microsoft.CodeAnalysis; 10 | using Microsoft.CodeAnalysis.CodeActions; 11 | using Microsoft.CodeAnalysis.CodeFixes; 12 | using Microsoft.CodeAnalysis.CSharp.Syntax; 13 | 14 | namespace Collections.Analyzer.CodeFixes 15 | { 16 | [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(RemoveRedundantMethodCallCodeFix))] 17 | [Shared] 18 | public class RemoveRedundantMethodCallCodeFix : CodeFixProvider 19 | { 20 | public override ImmutableArray FixableDiagnosticIds => ImmutableArray.Create( 21 | StringToArrayDiagnostic.RedundantStringToArrayRule.Id, 22 | ArrayToArrayDiagnostic.RedundantArrayToArrayRule.Id, 23 | EnumerableToArrayOnReturnDiagnostic.RedundantEnumerableToArrayRule.Id, 24 | AddRangeDiagnostic.AddRangeRule.Id, 25 | AssignEnumerableDiagnostic.AssignEnumerableRule.Id, 26 | ConstructorDiagnostic.ConstructorRule.Id, 27 | ObjectInitializerDiagnostic.RedundantArrayToArrayRule.Id, 28 | EnumerableToArrayOnReturnDiagnostic.RedundantEnumerableToArrayRule.Id, 29 | StringJoinToArrayDiagnostic.StringJoinToArrayRule.Id); 30 | 31 | public override FixAllProvider GetFixAllProvider() 32 | { 33 | return WellKnownFixAllProviders.BatchFixer; 34 | } 35 | 36 | public override async Task RegisterCodeFixesAsync(CodeFixContext context) 37 | { 38 | var root = await context.Document.GetSyntaxRootAsync(); 39 | var diagnostic = context.Diagnostics.First(); 40 | var invocationExpressionSyntax = root!.FindNode(context.Span) as InvocationExpressionSyntax; 41 | if (invocationExpressionSyntax == null) 42 | { 43 | var arg = root.FindNode(context.Span) as ArgumentSyntax; 44 | invocationExpressionSyntax = arg?.Expression as InvocationExpressionSyntax; 45 | } 46 | 47 | var name = (invocationExpressionSyntax?.Expression as MemberAccessExpressionSyntax)?.Name.Identifier; 48 | 49 | var title = string.Format(Resources.RemoveRedundantCall, name); 50 | 51 | context.RegisterCodeFix( 52 | CodeAction.Create( 53 | title, 54 | token => FixAsync(context.Document, invocationExpressionSyntax, token), 55 | title 56 | ), 57 | diagnostic 58 | ); 59 | } 60 | 61 | private static async Task FixAsync(Document document, 62 | InvocationExpressionSyntax? originalInvocationExpression, 63 | CancellationToken cancellationToken) 64 | { 65 | var expression = (originalInvocationExpression?.Expression as MemberAccessExpressionSyntax)?.Expression; 66 | 67 | if (expression == null) return document; 68 | 69 | var oldRoot = await document.GetSyntaxRootAsync(cancellationToken); 70 | var newRoot = oldRoot!.ReplaceNode(originalInvocationExpression!, expression); 71 | 72 | return document.WithSyntaxRoot(newRoot); 73 | } 74 | } 75 | } -------------------------------------------------------------------------------- /Collections.Analyzer/Diagnostics/CI0001/StringToArrayDiagnostic.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.Immutable; 3 | using System.Linq; 4 | using Microsoft.CodeAnalysis; 5 | using Microsoft.CodeAnalysis.CSharp; 6 | using Microsoft.CodeAnalysis.CSharp.Syntax; 7 | using Microsoft.CodeAnalysis.Diagnostics; 8 | 9 | namespace Collections.Analyzer.Diagnostics.CI0001 10 | { 11 | [DiagnosticAnalyzer(LanguageNames.CSharp)] 12 | public sealed class StringToArrayDiagnostic : DiagnosticAnalyzer 13 | { 14 | private static readonly IReadOnlyCollection Methods = 15 | new HashSet(new[] {nameof(Enumerable.ToArray), nameof(Enumerable.ToList)}); 16 | 17 | internal static readonly DiagnosticDescriptor RedundantStringToArrayRule = new( 18 | "CI0001", 19 | Resources.CI0001_Title, 20 | Resources.CI0001_Title, 21 | Categories.Performance, 22 | DiagnosticSeverity.Warning, 23 | true 24 | ); 25 | 26 | public override ImmutableArray SupportedDiagnostics => 27 | ImmutableArray.Create(RedundantStringToArrayRule); 28 | 29 | public override void Initialize(AnalysisContext context) 30 | { 31 | context.EnableConcurrentExecution(); 32 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); 33 | 34 | context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression); 35 | } 36 | 37 | private static void Analyze(SyntaxNodeAnalysisContext context) 38 | { 39 | var invocationExpression = (InvocationExpressionSyntax) context.Node; 40 | 41 | var redundantMethod = context.SemanticModel.GetSymbolInfo(invocationExpression).Symbol as IMethodSymbol; 42 | 43 | if (redundantMethod == null) return; 44 | 45 | if (invocationExpression.Parent is ForEachStatementSyntax) 46 | CheckRedundantStringConversion(context, redundantMethod, invocationExpression); 47 | else if (invocationExpression.Parent is MemberAccessExpressionSyntax parentExpression 48 | && context.SemanticModel.GetSymbolInfo(parentExpression).Symbol?.ContainingType.Name == 49 | nameof(Enumerable)) 50 | CheckRedundantStringConversion(context, redundantMethod, invocationExpression); 51 | } 52 | 53 | private static void CheckRedundantStringConversion(SyntaxNodeAnalysisContext context, 54 | IMethodSymbol methodSymbol, 55 | InvocationExpressionSyntax invocationExpression) 56 | { 57 | if (StringExtensions.ToCharArrayCalled(methodSymbol)) 58 | context.ReportDiagnostic(Diagnostic.Create(RedundantStringToArrayRule, 59 | invocationExpression.GetLocation(), 60 | methodSymbol.ToString())); 61 | else if (StringExtensions.IsLinqMethodCalledOnString(context, invocationExpression, methodSymbol, Methods)) 62 | context.ReportDiagnostic(Diagnostic.Create(RedundantStringToArrayRule, 63 | invocationExpression.GetLocation(), 64 | methodSymbol.ToString())); 65 | else if (StringExtensions.IsLinqMethodCalledOnMethod(context, invocationExpression, methodSymbol, Methods)) 66 | context.ReportDiagnostic(Diagnostic.Create(RedundantStringToArrayRule, 67 | invocationExpression.GetLocation(), 68 | methodSymbol.ToString())); 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /Collections.Analyzer/Resources.resx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 8 | 9 | 10 | 11 | text/microsoft-resx 12 | 13 | 14 | 1.3 15 | 16 | 17 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, 18 | PublicKeyToken=b77a5c561934e089 19 | 20 | 21 | 22 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, 23 | PublicKeyToken=b77a5c561934e089 24 | 25 | 26 | 27 | Redundant string conversion 28 | 29 | 30 | Remove method call {0} 31 | 32 | 33 | Redundant array conversion 34 | 35 | 36 | Redundant enumerable conversion 37 | 38 | 39 | Not optimal List<char> constructor usage 40 | 41 | 42 | Add ToCharArray call 43 | 44 | 45 | Replace with ToCharArray call 46 | 47 | 48 | Replace with Count call 49 | 50 | 51 | Not optimal count of collection items 52 | 53 | 54 | Collection initializer is used without capacity 55 | 56 | 57 | Initial collection capacity is less than amount of actual values 58 | 59 | 60 | Set actual capacity 61 | 62 | 63 | Any() is blocking on concurrent collections 64 | 65 | 66 | Replace with IsEmpty 67 | 68 | 69 | Consider using HashSet instead of array for Contains operations 70 | 71 | 72 | Array '{0}' is used with Contains() method. Consider using HashSet&lt;{1}&gt; for better performance 73 | 74 | 75 | HashSet<T> provides O(1) lookup time for Contains() operation, while array has O(n) time complexity 76 | 77 | 78 | Replace array with HashSet 79 | 80 | -------------------------------------------------------------------------------- /Collections.Analyzer/Diagnostics/CI0004/ListFromStringDiagnostic.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Immutable; 4 | using System.Linq; 5 | using Microsoft.CodeAnalysis; 6 | using Microsoft.CodeAnalysis.CSharp; 7 | using Microsoft.CodeAnalysis.CSharp.Syntax; 8 | using Microsoft.CodeAnalysis.Diagnostics; 9 | 10 | namespace Collections.Analyzer.Diagnostics.CI0004 11 | { 12 | [DiagnosticAnalyzer(LanguageNames.CSharp)] 13 | public class ListFromStringDiagnostic : DiagnosticAnalyzer 14 | { 15 | private static readonly IReadOnlyCollection Methods = 16 | new HashSet(new[] {nameof(Enumerable.ToArray), nameof(Enumerable.ToList)}); 17 | 18 | internal static readonly DiagnosticDescriptor ListFromStringRule = new( 19 | "CI0004", 20 | Resources.CI0004_Title, 21 | Resources.CI0004_Title, 22 | Categories.Performance, 23 | DiagnosticSeverity.Warning, 24 | true 25 | ); 26 | 27 | public override ImmutableArray SupportedDiagnostics => 28 | ImmutableArray.Create(ListFromStringRule); 29 | 30 | public override void Initialize(AnalysisContext context) 31 | { 32 | context.EnableConcurrentExecution(); 33 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); 34 | 35 | context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.ObjectCreationExpression); 36 | } 37 | 38 | private static void Analyze(SyntaxNodeAnalysisContext context) 39 | { 40 | var objectCreationExpression = (ObjectCreationExpressionSyntax) context.Node; 41 | 42 | if (objectCreationExpression.Type is GenericNameSyntax genericName 43 | && genericName.Identifier.ToString() == "List" 44 | && genericName.TypeArgumentList.Arguments.FirstOrDefault()?.ToString() == "char") 45 | { 46 | if (objectCreationExpression.ArgumentList?.Arguments.FirstOrDefault()?.Expression is 47 | InvocationExpressionSyntax 48 | invocationExpression 49 | && context.SemanticModel.GetSymbolInfo(invocationExpression).Symbol is IMethodSymbol method) 50 | CheckRedundantStringConversion(context, method, invocationExpression); 51 | else if (objectCreationExpression.ArgumentList?.Arguments.FirstOrDefault()?.Expression is 52 | IdentifierNameSyntax identifier 53 | && context.SemanticModel.GetTypeInfo(identifier).Type?.Name == nameof(String)) 54 | context.ReportDiagnostic(Diagnostic.Create(ListFromStringRule, identifier.GetLocation(), 55 | identifier.ToString())); 56 | } 57 | } 58 | 59 | private static void CheckRedundantStringConversion(SyntaxNodeAnalysisContext context, 60 | IMethodSymbol methodSymbol, 61 | InvocationExpressionSyntax invocationExpression) 62 | { 63 | if (StringExtensions.IsLinqMethodCalledOnString(context, invocationExpression, methodSymbol, Methods)) 64 | context.ReportDiagnostic(Diagnostic.Create(ListFromStringRule, invocationExpression.GetLocation(), 65 | methodSymbol.ToString())); 66 | else if (StringExtensions.IsLinqMethodCalledOnMethod(context, invocationExpression, methodSymbol, Methods)) 67 | context.ReportDiagnostic(Diagnostic.Create(ListFromStringRule, invocationExpression.GetLocation(), 68 | methodSymbol.ToString())); 69 | } 70 | } 71 | } -------------------------------------------------------------------------------- /Collections.Analyzer/Diagnostics/CI0003/EnumerableToArrayOnReturnDiagnostic.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Immutable; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.CodeAnalysis; 6 | using Microsoft.CodeAnalysis.CSharp; 7 | using Microsoft.CodeAnalysis.CSharp.Syntax; 8 | using Microsoft.CodeAnalysis.Diagnostics; 9 | 10 | namespace Collections.Analyzer.Diagnostics.CI0003 11 | { 12 | [DiagnosticAnalyzer(LanguageNames.CSharp)] 13 | public sealed class EnumerableToArrayOnReturnDiagnostic : DiagnosticAnalyzer 14 | { 15 | internal static readonly DiagnosticDescriptor RedundantEnumerableToArrayRule = new( 16 | "CI0003", 17 | Resources.CI0003_Title, 18 | Resources.CI0003_Title, 19 | Categories.Performance, 20 | DiagnosticSeverity.Warning, 21 | true 22 | ); 23 | 24 | public override ImmutableArray SupportedDiagnostics => 25 | ImmutableArray.Create(RedundantEnumerableToArrayRule); 26 | 27 | public override void Initialize(AnalysisContext context) 28 | { 29 | context.EnableConcurrentExecution(); 30 | context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); 31 | 32 | context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.InvocationExpression); 33 | } 34 | 35 | private static void Analyze(SyntaxNodeAnalysisContext context) 36 | { 37 | var invocationExpression = (InvocationExpressionSyntax) context.Node; 38 | 39 | if (!ExpressionExtensions.IsRedundantMethod(context, invocationExpression)) return; 40 | 41 | if (invocationExpression.Parent is not ReturnStatementSyntax) return; 42 | 43 | if (invocationExpression.Expression is MemberAccessExpressionSyntax 44 | { 45 | Expression: IdentifierNameSyntax identifier 46 | } 47 | && context.SemanticModel.GetTypeInfo(identifier).Type!.AllInterfaces.Any(o => 48 | o.Name == nameof(IEnumerable)) 49 | && GetReturnType(invocationExpression, context)?.Name == nameof(IEnumerable) 50 | ) 51 | { 52 | context.ReportDiagnostic(Diagnostic.Create(RedundantEnumerableToArrayRule, 53 | invocationExpression.GetLocation(), 54 | invocationExpression.ToString())); 55 | } 56 | else if (invocationExpression.Expression is MemberAccessExpressionSyntax 57 | { 58 | Expression: InvocationExpressionSyntax invocationExpressionSyntax 59 | } 60 | && GetReturnType(invocationExpressionSyntax, context)?.Name == nameof(IEnumerable) 61 | && context.SemanticModel.GetSymbolInfo(invocationExpressionSyntax).Symbol is IMethodSymbol ms 62 | && ms.ReturnType.AllInterfaces.Any(o => o.Name == nameof(IEnumerable))) 63 | { 64 | context.ReportDiagnostic(Diagnostic.Create(RedundantEnumerableToArrayRule, 65 | invocationExpression.GetLocation(), 66 | invocationExpression.ToString())); 67 | } 68 | } 69 | 70 | private static ITypeSymbol? GetReturnType(SyntaxNode? node, SyntaxNodeAnalysisContext context) 71 | { 72 | while (node != null) 73 | { 74 | switch (node) 75 | { 76 | case MethodDeclarationSyntax method: 77 | return GetType(context, method.ReturnType); 78 | case PropertyDeclarationSyntax property: 79 | return GetType(context, property.Type); 80 | default: 81 | node = node.Parent; 82 | break; 83 | } 84 | } 85 | 86 | return null; 87 | } 88 | 89 | private static ITypeSymbol? GetType(SyntaxNodeAnalysisContext context, ExpressionSyntax returnType) 90 | { 91 | var typeSymbol = context.SemanticModel.GetTypeInfo(returnType).Type as INamedTypeSymbol; 92 | 93 | if (typeSymbol == null) 94 | return null; 95 | 96 | if (typeSymbol is {IsGenericType: true, Name: nameof(Task)} 97 | or {IsGenericType: true, Name: nameof(ValueTask)}) 98 | { 99 | return typeSymbol.TypeArguments.FirstOrDefault(); 100 | } 101 | 102 | return typeSymbol; 103 | } 104 | } 105 | } --------------------------------------------------------------------------------