Generics HashSet<T> in C# - Learn with Examples
Introduction to Generics HashSet<T> in C#
Hey there, C# enthusiast! Have you ever needed a collection of unique elements? Maybe you’re tired of handling duplicate values in a list? Well, guess what? Generics HashSet<T> in C# is here to save the day!
Think of it like your VIP party list—you don’t want duplicates! If someone tries to enter twice, the security (HashSet) will stop them. Sounds cool, right? Let’s dive into it!
📚 What You Are Going to Learn in This Lesson
✔️ What Generics HashSet<T> in C# is and why it’s important
✔️ The syntax and how to use it properly
✔️ Real-world scenarios where it makes life easier
✔️ Multiple coding examples to boost your understanding
✔️ How it prevents duplicate values automatically
Buckle up! It’s going to be a fun ride. 😃
🤔 Why Use Generics HashSet<T> in C#?
Before we get our hands dirty with code, let’s understand why HashSet<T> is so useful.
✅ No Duplicates: It automatically removes duplicate values. You don’t have to check manually!
✅ Faster Lookups: It is faster than lists when checking for existing elements.
✅ Great for Unique Collections: Perfect when you need a collection of unique items, like product IDs or usernames.
For example, imagine you’re creating a system where users can vote only once. A HashSet<T> makes sure they don’t vote twice! 🚀
🛠 Syntax of Generics HashSet<T> in C#
Here’s how you declare a HashSet<T>:
HashSet<T> setName = new HashSet<T>();
- T is the data type (like
int
,string
, or a custom class). setName
is the variable name for the HashSet<T>.
Now, let’s see it in action!
🚀 Example 1: Basic HashSet<T> in C#
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> numbers = new HashSet<int>() { 1, 2, 3, 4, 5, 5, 2 };
Console.WriteLine("Unique numbers in HashSet:");
foreach (var num in numbers)
{
Console.WriteLine(num);
}
}
}
🖥️ Output:
Unique numbers in HashSet:
1
2
3
4
5
🔍 Explanation:
We added some duplicate numbers (
5
and2
).HashSet<T> automatically removed them! No duplicates allowed!
The loop prints only unique values.
Cool, right? Now, let’s level up! 🎮
🌍 Real-World Example: Unique Usernames
Imagine you’re building a registration system where users cannot have duplicate usernames. HashSet<T> makes this super easy!
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<string> usernames = new HashSet<string>();
// Adding usernames
usernames.Add("JohnDoe");
usernames.Add("Alice99");
usernames.Add("JohnDoe"); // Duplicate!
Console.WriteLine("Unique usernames:");
foreach (var username in usernames)
{
Console.WriteLine(username);
}
}
}
🖥️ Output:
Unique usernames:
JohnDoe
Alice99
🔍 Explanation:
We tried adding
"JohnDoe"
twice.HashSet<T> prevented the duplicate from being added.
The system keeps only unique usernames.
This makes HashSet<T> a perfect choice for storing unique user data! 🚀
🔄 Example 3: HashSet<T> Operations
Besides adding values, HashSet<T> also supports cool operations! Let’s see them in action:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> set1 = new HashSet<int>() { 1, 2, 3, 4, 5 };
HashSet<int> set2 = new HashSet<int>() { 4, 5, 6, 7, 8 };
// Union (Combine both sets)
set1.UnionWith(set2);
Console.WriteLine("After Union:");
Console.WriteLine(string.Join(", ", set1));
// Intersection (Find common elements)
set1.IntersectWith(new HashSet<int>() { 4, 5, 10 });
Console.WriteLine("After Intersection:");
Console.WriteLine(string.Join(", ", set1));
}
}
🖥️ Output:
After Union:
1, 2, 3, 4, 5, 6, 7, 8
After Intersection:
4, 5
🔍 Explanation:
UnionWith() combines two sets (removing duplicates).
IntersectWith() keeps only common elements.
HashSet<T> is great for mathematical operations like sets in algebra! 😃
🎯 Why is HashSet<T> Important?
✅ Boosts performance (faster searches than a List).
✅ Ensures data uniqueness without extra checks.
✅ Provides built-in set operations like Union and Intersection.
If your app deals with unique data, you NEED HashSet<T> in your toolbox! 🧰
🎬 Conclusion
Woohoo! 🎉 You just learned how Generics HashSet<T> in C# helps manage unique collections effortlessly. From storing unique usernames to performing fast lookups, it’s a must-have in C#.
Let’s recap:
✔️ No duplicates allowed in HashSet<T>!
✔️ Faster than lists for checking existing values.
✔️ Real-world uses like user registrations and mathematical operations.
Now, go ahead and use HashSet<T> in your projects! 🚀
⏭️ Next What?
In the next chapter, you’ll explore Threads in C#! Imagine running multiple tasks at once—sounds exciting, right? Stay tuned for more coding fun! 😃
💬 Got questions? Drop them below. Keep learning, keep coding! 🎯