Monday, August 18, 2014

PCL Tips and Tricks: String sbyte* constructor

The introduction of Portable Class Libraries, PCL, considerably facilitates the sharing of functionality across managed Microsoft and Xamarin platforms. I am very enthusiastic about the PCL concept, and I have ported several .NET Framework open source projects to Portable Class Libraries. Along the way I have stumbled across various issues of making .NET Framework source code PCL compliant. In this mini-series I'll share my experiences and workarounds to facilitate the transfer to PCL for other developers.

Some of the PCL profiles do support unsafe code, in particular those profiles targeting Windows 8 and Windows Phone 8.1 (non-Silverlight). This means that it is possible to include for example pointers in the PCL code. On the other hand, methods dealing with unsafe code are rare in the .NET Portable Subset.

One case I ran into the other day is the String constructor. In .NET Framework, there are a few constructors taking an sbyte pointer as an argument, for example:

public String(sbyte* value, int startIndex, int length)

This constructor is not available in the .NET Portable Subset, so I had to come up with a replacement. And I came up with this portable method:

static unsafe String NewString(
    sbyte* value, int startIndex, int length)
{
  var chars = new char[length];
  for (var i = 0; i < length; ++i)
    chars[i] = (char)value[startIndex + i];
  return new String(chars);
}

So, instead of calling new String(...), the calls were changed to NewString(...).

I am still not entirely pleased with this approach of adding a new method to solve the issue. If any blog reader has a leaner solution to this issue, I am all ears.