Silverlight 2: Encoding class GetString confusion
Share
I recently discovered a breaking change in the System.Text.Encoding class in Silverlight 2; the GetString(Byte[]) method, a long-time public method in mscorlib.dll, has changed protection levels to internal. So, the following banal snippet of code will compile in any previous .NET runtime:
public void AttemptToGetString()
{
MemoryStream ms = new MemoryStream();
string text = Encoding.Unicode.GetString(ms.ToArray());
}
Create that snippet in Silverlight, however, and you’ll be greeted with ‘System.Text.Encoding.GetString(byte[])’ is inaccessible due to its protection level‘ as expected. If you check out the code you’ll notice that this once-public citizen was not doing much more than its cousin, the still-public GetString(Byte[], int, int):
internal virtual string GetString(byte[] bytes)
{
if (bytes == null)
{
throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array"));
}
return this.GetString(bytes, 0, bytes.Length);
}
So, we should be able to call the slightly bothersome public method, pass in the the extra integer values, and be on our way. And while this is true, notice that somewhere in Silverlight there is an extension method which appears to be a replacement for the public method, and that there is no way to call it (it’s shacking up with System.Net.WebClientExtensions, another private affair).
I’m not sure where this kind of change comes from and whether it qualifies for Connect, but hopefully if you run into this situation like I did, you’ll find this post, toss in a few more integers or your own extension method, and be on your way. I don’t know why this method needs to be internal in Silverlight 2.
Socialized