System.Text.Encoding question

Would it be possible to add GetString(byte[]) to System.Text.Encoding ?

Or is there a work-around?

You need to GetChar from byte and then use that to construct new string.

This could look like this :

var readBuffer = new byte[10];
Debug.Print(new String(Encoding.UTF8.GetChars(readBuffer)));

Don’t forget that with extension methods, you can add your own methods to existing classes. So, here’s an example of creating an extension method for an array of bytes. I called the extension method ToStringFromUTF8.

To run the example, you can put it all in Program.cs of a throwaway app. I typically create a separate file for each class’s extensions, or at the least, each related group of extensions.

using System;
using System;
using System.Threading;

using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;

using GHIElectronics.NETMF.FEZ;

// Required for NETMF to recognized extension methods
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class ExtensionAttribute : Attribute { }
}

// Extension methods for byte[] - typically would be put in a separate file
public static class ByteArrayExtensions
{
    // Method to create a string from UTF8-encoded bytes - be careful about null "this" being passed in
    public static string ToStringFromUTF8(this byte[] bytes)
    {
        return null == bytes ? String.Empty : new String(System.Text.Encoding.UTF8.GetChars(bytes));
    }
}

namespace FEZ_Domino_Application3
{
    public class Program
    {
        public static void Main()
        {

            string s = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";

            byte[] bytes = System.Text.UTF8Encoding.UTF8.GetBytes(s);

            Debug.Print(bytes.ToStringFromUTF8());
           
        }
    }
}