C#:C# HashSet<T> and ValueTuples (Multiple Return Values)
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:

ParameterTypeDescription
HashSet<T>CollectionGuarantees set uniqueness with O(1) lookup.
ValueTupleStructStack-allocated tuple with named elements.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test C# on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C# Online Compiler