bhylu.com

Advertisements

C# HashSet<T>

Reject a duplicate enrolment code through the collection’s insertion result.

How it works

HashSet<T> stores unique values under a chosen equality relation. Add returns whether a new value was inserted, making duplicate handling explicit. Hash-based membership has useful average cost but not a universal constant worst-case promise. Sets express membership, not arrival order or a persistent record history. Keep identifiers normalized according to the domain, and align equality with hashing when defining a custom key type.

Run it locally

Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-build

Use the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.

Download the complete C# source as Program.cs.

Example

C# 14 · Program.cs

using System;
using System.Collections.Generic;

internal static class Program
{
    private static void Main(string[] args)
    {
        var codes = new HashSet<string>(StringComparer.Ordinal) { "W-17" };
        Console.WriteLine($"Duplicate added: {codes.Add("W-17")}");
        Console.WriteLine($"New added: {codes.Add("W-18")}");
        Console.WriteLine($"Unique codes: {codes.Count}");
    }
}

Expected result

Duplicate added: False
New added: True
Unique codes: 2

The repeated code leaves membership unchanged. Ordinal comparison treats different casing as different codes under this explicit policy. If the business instead ignores case, choose that comparer rather than applying inconsistent ad hoc transformations at different call sites. Keep a separate ordered sequence when both membership and arrival order are required.

Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.