Target Typing Collections
Let the target type drive collection creation.
What Is Target Typing?
Target typing means the compiler infers what a collection expression should build from the context where it is used, rather than from an explicit type on the right-hand side.
using System;
int[] numbers = [1, 2, 3]; // target type is int[]
Console.WriteLine(numbers.GetType().Name); // Int32[]The Target Drives the Type
The same literal becomes a different concrete type depending on the variable, parameter, or return type it flows into.
using System;
using System.Collections.Generic;
int[] asArray = [1, 2, 3];
List<int> asList = [1, 2, 3];
Console.WriteLine(asArray is int[]); // True
Console.WriteLine(asList is List<int>); // TrueAll lessons in this course
- Collection Expression Syntax
- The Spread Element
- Target Typing Collections
- Collection Builders