csharp / intermediate
Snippet
Generic Array Mapping without Linq
Understanding how to manually implement generic transformations on arrays helps master both Generics and Function delegates. This approach avoids overhead from external libraries and focuses on core language efficiency.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
public TOutput[] MapArray<TInput, TOutput>(TInput[] input, Func<TInput, TOutput> mapper){TOutput[] result = new TOutput[input.Length];for (int i = 0; i < input.Length; i++){result[i] = mapper(input[i]);}return result;}// Usageint[] nums = { 1, 2, 3 };string[] strings = MapArray(nums, x => x.ToString());
Breakdown
1
<TInput, TOutput>
Defines generic type parameters for flexibility with different data types.
2
new TOutput[input.Length]
Initializes a new array of the target type with the same size as the input.
3
mapper(input[i])
Applies the transformation function to each element individually.