I’m continuing my discussion on proposed C# 7 features. Let’s take a brief look at Slices. The full discussion is here on GitHub. Please add your thoughts on that issue, rather than commenting directly to me. That ensures that your thoughts directly reach the team.
Let’s start with the problem that Slices are designed to solve. Arrays are a very common data structure (not just in C#, but in many languages.) That said, it’s often that you work with a subset of an entire array. You’ll likely want to send a subset of an array to some method for changes, or read only processing. That leaves you with two sub-optimal choices. You can either copy the portion of the Array that you want to send to another method. Or, you use the entire array, and pass indices for the portion that should be used.
The first approach requires often copying sub-arrays for use by APIs. The second approach means trusting the called method to not move outside the bounds of the sub-array.
Slices would provide a third approach; one that enforces the boundaries to the proper subset of an array, without requiring copies of the original data structure.
The feature requires two pieces. First, there is a
Slice<T> class that would support a slice of an array. There is also a related
ReadOnlySlice<T> class that would support a readonly slice of an array.
In addition, the C# Language would support features designed to create those slice objects from another array:
Person slice = people.GetSlice(3, 9);
byte bytes = GetFromNative();
There is quite a bit of discussion about the final implementation, including whether or not CLR support would be needed. Some of that discussion moved to the C# Language Design Notes here.
This post is somewhat light on details, because the syntax and the full feature implementation is still under discussion. You can look at one implementation here: https://github.com/dotnet/corefxlab/tree/master/src/System.Slices
I will write new posts as the feature list and the syntax and impementation become more concrete.