Typing in something like Encoding.UTF8.GetString(...)
and Encoding.UTF8.GetBytes(...)
everywhere in your code could be eliminated by a helper UTF8
type:
public class UTF8_Should
{
[Test]
public void Convert()
{
var text = "Hello World";
byte[] array = (UTF8)text;
string copy = (UTF8)array;
Assert.AreEqual(text, copy);
}
}
Where:
struct UTF8
{
public static implicit operator UTF8(byte[] array) => new UTF8(Encoding.UTF8.GetString(array));
public static implicit operator string(UTF8 utf8) => utf8.Text;
public static implicit operator UTF8(string text) => new UTF8(text);
public static implicit operator byte[](UTF8 utf8) => Encoding.UTF8.GetBytes(utf8.Text);
public UTF8(string text) => Text = text;
string Text { get; }
}
1 Answer 1
You don't care about null
references?
IMO you create an object in order just to do something, that is more suitable for the concept of extensions:
public static class StringExtensions
{
public static byte[] ToUTF8Bytes(this string text)
{
return Encoding.UTF8.GetBytes(text);
}
public static string ToUTF8(this byte[] bytes)
{
return Encoding.UTF8.GetString(bytes);
}
}
Assert.AreEqual(text, text.ToUTF8Bytes().ToUTF8());
The benefit of the extension methods is that you don't have to remember that you've created the UTF8
struct somewhere, because it will show up in the intellisence.
-
\$\begingroup\$ 1) C# 8 supports non nullable references. 2) We will lost a possibility to declare parameters of type UTF8 which makes sense to have in, for example, IoT domain - you might would like to know how the string is about to be serialized. \$\endgroup\$Dmitry Nogin– Dmitry Nogin2020年04月04日 15:56:35 +00:00Commented Apr 4, 2020 at 15:56