C# Collections: Sets
In this C# lesson, we will study Sets through small executable cases. First we will make the normal result clear; then inspect data flow, ownership, failure behavior, and the caller contract before adding framework or infrastructure complexity.
Professional code is readable under change. A future developer should be able to identify which input is trusted, who may update state, where I/O happens, and how an expected error reaches a caller without reconstructing the whole application.
What You Will Build
Five focused C# programs for Sets. Each has a visible result, an explicit contract, and a next change to test so the lesson becomes reusable knowledge rather than passive reading.
Example 1: Return one typed value
Let’s isolate one C# Collections rule together. Run it, trace the inputs and output, then change one boundary value before reusing the pattern. Small observable programs turn syntax into a reliable engineering habit.
Keep contracts explicit: validate data before use, make ownership and mutation visible, and return a named result or failure a caller can test. Static types and a successful build help, but runtime boundaries still need intentional checks.
C#
using System;
class Program {
static int Square(int value) => value * value;
static void Main() => Console.WriteLine(Square(7));
}Expected Result
49
Try next: make the nearest empty, invalid, missing, or boundary case observable instead of leaving behavior to an unchecked assumption.
Example 2: Use a generic collection
Let’s isolate one C# Collections rule together. Run it, trace the inputs and output, then change one boundary value before reusing the pattern. Small observable programs turn syntax into a reliable engineering habit.
Keep contracts explicit: validate data before use, make ownership and mutation visible, and return a named result or failure a caller can test. Static types and a successful build help, but runtime boundaries still need intentional checks.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() { var values = new List<int> { 2, 3, 4 }; Console.WriteLine(values.Count); }
}Expected Result
3
Try next: make the nearest empty, invalid, missing, or boundary case observable instead of leaving behavior to an unchecked assumption.
Example 3: Transform data with LINQ
Let’s isolate one C# Collections rule together. Run it, trace the inputs and output, then change one boundary value before reusing the pattern. Small observable programs turn syntax into a reliable engineering habit.
Keep contracts explicit: validate data before use, make ownership and mutation visible, and return a named result or failure a caller can test. Static types and a successful build help, but runtime boundaries still need intentional checks.
C#
using System;
using System.Linq;
class Program {
static void Main() { var result = new[] { 1, 2, 3 }.Select(value => value * value); Console.WriteLine(string.Join(",", result)); }
}Expected Result
1,4,9
Try next: make the nearest empty, invalid, missing, or boundary case observable instead of leaving behavior to an unchecked assumption.
Example 4: Await a typed task
Let’s isolate one C# Collections rule together. Run it, trace the inputs and output, then change one boundary value before reusing the pattern. Small observable programs turn syntax into a reliable engineering habit.
Keep contracts explicit: validate data before use, make ownership and mutation visible, and return a named result or failure a caller can test. Static types and a successful build help, but runtime boundaries still need intentional checks.
C#
using System;
using System.Threading.Tasks;
class Program {
static async Task<string> LabelAsync() { await Task.Yield(); return "ready"; }
static async Task Main() => Console.WriteLine(await LabelAsync());
}Expected Result
ready
Try next: make the nearest empty, invalid, missing, or boundary case observable instead of leaving behavior to an unchecked assumption.
Example 5: Handle an expected exception
Let’s isolate one C# Collections rule together. Run it, trace the inputs and output, then change one boundary value before reusing the pattern. Small observable programs turn syntax into a reliable engineering habit.
Keep contracts explicit: validate data before use, make ownership and mutation visible, and return a named result or failure a caller can test. Static types and a successful build help, but runtime boundaries still need intentional checks.
C#
using System;
class Program {
static void Main() { try { throw new InvalidOperationException("missing value"); }
catch (InvalidOperationException error) { Console.WriteLine(error.Message); } }
}Expected Result
missing value
Try next: make the nearest empty, invalid, missing, or boundary case observable instead of leaving behavior to an unchecked assumption.
Example 6: Make the input visible
Start by naming the value the next line depends on. This keeps the lesson input explicit before we apply a transformation or call an external boundary. We are applying that habit while revisiting C# Collections: Sets.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C#
using System;
public class Program
{
public static void Main()
{
var lesson = "C Collections Sets";
Console.WriteLine(lesson.ToUpperInvariant());
}
}Expected Result
C COLLECTIONS SETS
Try next: Replace the sample value with one from your own notes, predict the result, and then run it.
Example 7: Guard an empty boundary
A small guard makes the allowed and rejected path visible. We want a caller to receive an intentional result instead of discovering an unexplained failure later. We are applying that habit while revisiting C# Collections: Sets.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C#
using System;
public class Program
{
public static void Main()
{
var lesson = "C Collections Sets";
Console.WriteLine(lesson.ToUpperInvariant());
}
}Expected Result
C COLLECTIONS SETS
Try next: Try an empty value as well as the normal value and describe why the two outcomes differ.
Example 8: Keep the transformation pure
This step returns a value instead of mixing the rule with display or storage work. That separation gives us a small unit we can run, test, and reuse. We are applying that habit while revisiting C# Collections: Sets.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C#
using System;
public class Program
{
public static void Main()
{
var lesson = "C Collections Sets";
Console.WriteLine(lesson.ToUpperInvariant());
}
}Expected Result
C COLLECTIONS SETS
Try next: Call the same rule twice with different inputs and confirm that each result depends only on its input.
Example 9: Make a branch deliberate
Use a named branch where the business rule changes. A future reader should be able to point at the condition and state the result for both sides. We are applying that habit while revisiting C# Collections: Sets.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C#
using System;
public class Program
{
public static void Main()
{
var lesson = "C Collections Sets";
Console.WriteLine(lesson.ToUpperInvariant());
}
}Expected Result
C COLLECTIONS SETS
Try next: Change the boundary value by one and explain exactly which branch becomes active.
Example 10: Use a collection without hidden mutation
Collections become safer when we can see which value is read, which value is derived, and whether the original collection remains owned by the caller. We are applying that habit while revisiting C# Collections: Sets.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C#
using System;
public class Program
{
public static void Main()
{
var lesson = "C Collections Sets";
Console.WriteLine(lesson.ToUpperInvariant());
}
}Expected Result
C COLLECTIONS SETS
Try next: Add one more item and predict the derived result before executing the code.
Example 11: Return a named outcome
A named outcome is easier to test than an implied side effect. We can now distinguish a successful path from a rejected path without guessing from console noise. We are applying that habit while revisiting C# Collections: Sets.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C#
using System;
public class Program
{
public static void Main()
{
var lesson = "C Collections Sets";
Console.WriteLine(lesson.ToUpperInvariant());
}
}Expected Result
C COLLECTIONS SETS
Try next: Rename the outcome in your own words while preserving the same success and failure rule.
Example 12: Trace a small loop
Work through one value at a time. The point is not to memorize syntax; it is to see how the accumulator or output changes after each repeatable step. We are applying that habit while revisiting C# Collections: Sets.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C#
using System;
public class Program
{
public static void Main()
{
var lesson = "C Collections Sets";
Console.WriteLine(lesson.ToUpperInvariant());
}
}Expected Result
C COLLECTIONS SETS
Try next: Use a shorter collection first, then add one value and trace the extra iteration aloud.
Example 13: Keep display at the edge
The core rule prepares a value, while the outer line decides how to show it. That keeps the result usable by a UI, test, API, or command-line caller. We are applying that habit while revisiting C# Collections: Sets.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C#
using System;
public class Program
{
public static void Main()
{
var lesson = "C Collections Sets";
Console.WriteLine(lesson.ToUpperInvariant());
}
}Expected Result
C COLLECTIONS SETS
Try next: Change only the display text and verify that the underlying rule and result stay unchanged.
Example 14: Test the closest boundary
A useful example includes the nearest boundary, not only the happy path. We are making the behavior inspectable before a real caller relies on it. We are applying that habit while revisiting C# Collections: Sets.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C#
using System;
public class Program
{
public static void Main()
{
var lesson = "C Collections Sets";
Console.WriteLine(lesson.ToUpperInvariant());
}
}Expected Result
C COLLECTIONS SETS
Try next: Try the lowest supported value and then one value just outside the accepted range.
Example 15: Write a tiny regression check
A compact assertion turns the lesson into a repeatable promise. It helps us catch a changed rule before a larger program hides the source of the mistake. We are applying that habit while revisiting C# Collections: Sets.
Keep the example small enough to trace. First predict the normal result; then change one input and explain the boundary result in your own words.
C#
using System;
public class Program
{
public static void Main()
{
var lesson = "C Collections Sets";
Console.WriteLine(lesson.ToUpperInvariant());
}
}Expected Result
C COLLECTIONS SETS
Try next: Deliberately change the expected value once, observe the failed check, and then restore the correct contract.
Design Review and Worked Trace
Review C# Collections: Sets as a full trace: input, validation, calculation or side effect, output, and cleanup. State the normal result, then state the boundary behavior. If either is hard to explain, split the work into a smaller function with a narrower contract.
Keep secret values and privileged decisions outside display code. Authentication establishes an identity; authorization decides what that identity may do. Check both close to protected operations, and use intentional failure responses rather than leaking internal details or crashing generically.
- Run the normal input and record the exact result.
- Test an empty, malformed, or boundary input deliberately.
- Keep state, ownership, and side effects visible to the caller.
- Return a result or named failure that can be tested.
- Never log credentials, tokens, or sensitive input.
This discipline makes C# code easier to review, safer to change, and more useful in production than a collection of untested syntax fragments.
Common Mistakes
- Skipping input validation because a local example happened to work.
- Hiding mutation, ownership, or failure behavior inside a convenient shortcut.
- Using a client-side display rule as the only protection for sensitive work.
- Copying code without changing an input to prove its contract.
