Thursday, December 21, 2017

How to Use Span


I've read plenty of articles about Span over the past year or two, and have been following its development from a distance, without actually trying any of the early iterations of it.  When Microsoft released a blog post welcoming Span, I figured it was finally time to try it out myself.


Where Is It?

Amazingly, the mentioned post above, and even the Channel 9 video C# 7.2: Understanding Span, never actually mention how to get Span compiling.  Searching for people that have actually used it, turned up nothing.

It wasn't until I read a comment on the article that I saw that you still need to reference the Nuget library System.Memory to get it to work.  Even more, the library is still in pre-release, so it is not actually officially released yet.  Based on the wording of the announcement post, this was surprising.

It appears that .NET Core 2.1 (and I assume .NET Standard 2.1) will have full support, as well as the additional library changes they keep mentioning, that have all of the overloads supporting span.

Adding Support

Anyways, the only thing you need to do, once you update to Visual Studio 2017 15.5, is to add the nuget package.

Install-Package System.Memory -Prerelease

You may still get some red squigglies with some code, as the editor doesn't have full support for it yet, but the following should compile.

var array = new int[10];
Span span = array;