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
newsyntax.Syntax:
[with(arguments), ...elements]
Examples
- Set Capacity
- Set Comparer
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
unionkeyword followed by the allowed types:public union Pet(Cat, Dog, Bird);Key Features:
Implicit Conversion: You can assign a
Dogdirectly to aPetvariable without casting.Exhaustive Switching: The compiler checks your
switchexpressions 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"];