VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/c-sharp-check-if-hashset-and-the-specified-collection-contain-the-same-elements/

⇱ C# | Check if HashSet and the specified collection contain the same elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C# | Check if HashSet and the specified collection contain the same elements

Last Updated : 11 Jul, 2025

Here's an example code that demonstrates how to use the Overlaps method to check if a HashSet and a specified collection share common elements in C#:


Output
Do set1 and list1 have common elements? True
Do set1 and list2 have common elements? False

A HashSet is an unordered collection of the unique elements. It comes under System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet.SetEquals(IEnumerable) Method is used to check if a HashSet and the specified collection contain the same elements or not. 

Syntax:

mySet1.SetEquals(mySet2);

Here, mySet1 and mySet2 are HashSets objects. 

Return Type: This method return True if the mySet1 is equal to mySet2 else returns False

Exception: This method will give ArgumentNullException if the HashSet is null

Below given are some examples to understand the implementation in a better way: 

Example 1: 

Example 2: 

Comment

Explore