Skip to main content

ListOrListReturningMethodFollowedByToList

Diagnostic Rule Overview

FieldValue
IDSHIMMER1013
Analyzer titleA list creation expression or list-returning method should not be followed by .ToList()
Analyzer message.ToList() is redundant
Code fix titleRemove redundant .ToList()
Default severityWarning
Minimum framework/language versionN/A
CategoryShimmeringUsage
Link to codeListOrListReturningMethodFollowedByToListAnalyzer.cs
Code fix exists?Yes

Detailed Explanation

Calling .ToList() on an existing list or a method call that returns a List<T> is redundant and wastes memory because .ToList() will always create and allocate a new list, copying the elements.

Examples

Flagged code:

using System.Collections.Generic;
using System.Linq;

namespace Tests;
class Test
{
void Do()
{
List<int> MyList = new List<int>().ToList();
}
}

Fixed code:

using System.Collections.Generic;
using System.Linq;

namespace Tests;
class Test
{
void Do()
{
List<int> MyList = new List<int>();
}
}

Justification of the Severity

While this does not cause a crash or correctness issue, calling .ToList() on an expression that is already a List<T> creates an unnecessary allocation and loop, which degrades performance without any benefit.