3
\$\begingroup\$

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; }
}
asked Apr 3, 2020 at 21:16
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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.

answered Apr 4, 2020 at 5:26
\$\endgroup\$
1
  • \$\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\$ Commented Apr 4, 2020 at 15:56

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.