Skip to main content

ArrayOrArrayReturningMethodFollowedByToArray

Diagnostic Rule Overview

FieldValue
IDSHIMMER1012
Analyzer titleAn array creation expression or array-returning method should not be followed by .ToArray()
Analyzer message.ToArray() is redundant
Code fix titleRemove redundant .ToArray()
Default severityWarning
Minimum framework/language versionN/A
CategoryShimmeringUsage
Link to codeArrayOrArrayReturningMethodFollowedByToArrayAnalyzer.cs
Code fix exists?Yes

Detailed Explanation

Calling .ToArray() on an existing array is redundant and wastes memory because .ToArray() will always create/allocate a new array.

Examples

Flagged code:

using System.Linq;

namespace Tests;
class Test
{
void Do()
{
var array = "a b".Split(' ').ToArray();
}
}

Fixed code:

using System.Linq;

namespace Tests;
class Test
{
void Do()
{
var array = "a b".Split(' ');
}
}

Justification of the Severity

While this is not a bug, this will slow down your code and increase memory usage with no benefits. As a reminder, calling .ToArray() on an existing array is not a no-op but rather creates and allocates a new array, so it has costs but not benefits.

Inspiration

This was inspired by @Treit's blog post https://mtreit.com/programming,/.net/2024/07/30/ToList.html. The same material was also covered in this YouTube video.