Sunday, April 5, 2026

C# 15 powerful features

1. Collection Expression Arguments

You can now pass arguments directly to a collection's underlying constructor or factory method using the with(...) syntax. This must be the first element inside the collection expression brackets [...].

  • Purpose: Allows you to set initial properties like capacity or comparers without reverting to traditional new syntax.

  • Syntax: [with(arguments), ...elements]

Examples

  • Set Capacity         
List<string> names = [with(capacity: 10), "A", "B"];

  • Set Comparer
HashSet<string> set = [with(StringComparer.Ordinal), "a", "A"];

2. Union Types

Union types allow a single variable to hold one of several specific "case types." This is a major step forward for type safety and functional programming patterns in C#.

  • Declaration: Use the union keyword followed by the allowed types: public union Pet(Cat, Dog, Bird);

  • Key Features:

    • Implicit Conversion: You can assign a Dog directly to a Pet variable without casting.

    • Exhaustive Switching: The compiler checks your switch expressions to ensure every possible case of the union is handled. If you miss a type, you get a compiler error.

  • Current Status: Introduced in .NET 11 previews. Some advanced features (like union member providers) are still in development.

Comparison: Traditional vs. New Syntax

Before (Collection Initializers):

var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Hi" };

After (Collection Expressions):

HashSet<string> set = [with(StringComparer.OrdinalIgnoreCase), "Hi"];


Cheers
Samitha