Skip to main content

HashSetOrHashSetReturningMethodFollowedByToHashSet

Diagnostic Rule Overview

FieldValue
IDSHIMMER1014
Analyzer titleA HashSet creation expression, identifier, or HashSet-returning method should not be followed by .ToHashSet()
Analyzer message.ToHashSet() is redundant
Code fix titleRemove redundant .ToHashSet()
Default severityWarning
Minimum framework/language versionN/A
CategoryShimmeringUsage
Link to codeHashSetOrHashSetReturningMethodFollowedByToHashSetAnalyzer.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.