Friday, May 9, 2014

PCL Tips and tricks: ASCIIEncoding

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.

It appears to be very common that .NET Framework class libraries containing some kind of text processing relies on the ASCIIEncoding class, or alternatively the Encoding.ASCII static property.

ASCIIEncoding is not portable, but fortunately it can very easily replaced with another encoding that is available in (I think) all PCL profiles, namely UTF8Encoding. The UTF-8 encoding contains the ASCII character set as a sub-set, and it is even stated in the MSDN documentation for Encoding.ASCII that:

If your application requires 8-bit encoding (which is sometimes incorrectly referred to as "ASCII"), the UTF-8 encoding is recommended over the ASCII encoding. For the characters 0-7F, the results are identical, but use of UTF-8 avoids data loss by allowing representation of all Unicode characters that are representable. Note that the ASCII encoding has an 8th bit ambiguity that can allow malicious use, but the UTF-8 encoding removes ambiguity about the 8th bit.

So, whenever encountering ASCIIEncoding or Encoding.ASCII in source code that you are porting to PCL, simply replace it with UTF8Encoding and Encoding.UTF8, respectively.

1 comment: