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.
Bill Wagner is one of the world's foremost C# developers and a member of the ECMA C# Standards Committee. He is President of the Humanitarian Toolbox, has been awarded Microsoft Regional Director and .NET MVP for 10+years, and was recently appointed to the .NET Foundation Advisory Council. Wagner currently works with companies ranging from start-ups to enterprises improving the software development process and growing their software development teams.