C#•Sets & Tuples
C# HashSet<T> and ValueTuples (Multiple Return Values)
Explore HashSet for unique items and C# 7+ ValueTuples for zero-allocation structured returns.
Syntax
var set = new HashSet<int> { 1, 2, 2 };
(string name, int port) = GetStatus();
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| HashSet<T> | Collection | Guarantees set uniqueness with O(1) lookup. |
| ValueTuple | Struct | Stack-allocated tuple with named elements. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C# locally:
using System;
using System.Collections.Generic;
public class Program {
// Function returning ValueTuple
public static (string Service, int Port, bool IsActive) GetEndpointConfig() {
return ("AuthService", 8080, true);
}
public static void Main() {
// 1. HashSet deduplication
var userRoles = new HashSet<string> { "ADMIN", "EDITOR", "ADMIN", "VIEWER" };
Console.WriteLine($"Unique Roles Count: {userRoles.Count}");
// 2. Unpacking ValueTuple
var (service, port, isActive) = GetEndpointConfig();
Console.WriteLine($"Service: {service} on port {port} (Active: {isActive})");
}
}Expected Output:
Unique Roles Count: 3 Service: AuthService on port 8080 (Active: true)
How It Works: Step-by-Step
- Lines 6-8: Defines method returning named ValueTuple.
- Line 12: HashSet automatically deduplicates "ADMIN".
- Line 16: Deconstructs tuple fields directly into local variables.
Key Concepts
- ValueTuples are lightweight value types (structs) on the stack.
- HashSet eliminates duplicates automatically upon insertion.
Common Mistake: Using legacy System.Tuple instead of modern ValueTuple
System.Tuple allocates a heap object; modern C# (x, y) ValueTuple is a zero-allocation struct.
❌ Incorrect
Tuple<int, int> t = new Tuple<int, int>(1, 2); // Heap allocated
✅ Correct
var t = (1, 2); // Lightweight stack-allocated ValueTuple
Related C# Tutorials & Compiler
C# List<T> and LINQ Queries: Where, Select, and Aggregate
Master dynamic List<T> collections and powerful LINQ queries (Where, Select, Sum).
C# Dictionary<TKey, TValue>: Hash Table Operations
Store and retrieve key-value pairs using Dictionary<TKey, TValue> with TryGetValue.
C# String Methods, String Interpolation, and StringBuilder
Master text manipulation with string methods, raw string literals, and StringBuilder.
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.