HashSetOrHashSetReturningMethodFollowedByToHashSet
Diagnostic Rule Overview
| Field | Value |
|---|---|
| ID | SHIMMER1014 |
| Analyzer title | A HashSet creation expression, identifier, or HashSet-returning method should not be followed by .ToHashSet() |
| Analyzer message | .ToHashSet() is redundant |
| Code fix title | Remove redundant .ToHashSet() |
| Default severity | Warning |
| Minimum framework/language version | N/A |
| Category | ShimmeringUsage |
| Link to code | HashSetOrHashSetReturningMethodFollowedByToHashSetAnalyzer.cs |
| Code fix exists? | Yes |
Detailed Explanation
Calling .ToHashSet() on an existing HashSet<T> is redundant and wastes memory because .ToHashSet() will always create and allocate a new HashSet<T> and populate it.
Examples
Flagged code:
using System.Collections.Generic;
using System.Linq;
namespace Tests;
class Test
{
void Do()
{
HashSet<int> MyHashSet = new HashSet<int>().ToHashSet();
}
}
Fixed code:
using System.Collections.Generic;
using System.Linq;
namespace Tests;
class Test
{
void Do()
{
HashSet<int> MyHashSet = new HashSet<int>();
}
}
Justification of the Severity
Calling .ToHashSet() on an expression that is already a HashSet<T> creates a completely redundant set object, generating useless heap allocations.