Convert strings to bytes with an explicit UTF-8 contract

A string becomes bytes only after you choose a representation. For network payloads, files and hashes, make that representation part of the contract. UTF-8 is a useful choice when both producer and consumer agree to it. Reading the internal memory of a .NET string does not create a portable text format.

A .NET string stores UTF-16 code units. Its Length is therefore neither a UTF-8 byte count nor a general count of visible characters. An emoji can occupy two UTF-16 code units and four UTF-8 bytes. A visible accented character can also have more than one Unicode representation.

Encode and decode strictly

Create a .NET 10 console project with dotnet new console -n Utf8Demo -f net10.0, replace Program.cs, then run dotnet run --project Utf8Demo from the parent directory.

C#
using System;
using System.Linq;
using System.Text;

var utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false,
	throwOnInvalidBytes: true);
var text = "café 🚀";
var bytes = utf8.GetBytes(text);
Console.WriteLine($"UTF-16 units={text.Length}");
Console.WriteLine($"UTF-8 bytes={bytes.Length}");
Console.WriteLine(Convert.ToHexString(bytes));
Console.WriteLine($"Round trip={utf8.GetString(bytes) == text}");

try {
	utf8.GetString(new byte[] { 0xC3, 0x28 });
} catch (DecoderFallbackException) {
	Console.WriteLine("Rejected invalid UTF-8");
}

try {
	utf8.GetBytes("\uD800");
} catch (EncoderFallbackException) {
	Console.WriteLine("Rejected unpaired surrogate");
}

var composed = "é";
var decomposed = "e\u0301";
Console.WriteLine($"Raw bytes equal={utf8.GetBytes(composed).SequenceEqual(utf8.GetBytes(decomposed))}");
Console.WriteLine($"Form C equal={composed.Normalize(NormalizationForm.FormC) == decomposed.Normalize(NormalizationForm.FormC)}");

Expected output:

Plain text
UTF-16 units=7
UTF-8 bytes=10
636166C3A920F09F9A80
Round trip=True
Rejected invalid UTF-8
Rejected unpaired surrogate
Raw bytes equal=False
Form C equal=True

The strict encoder rejects an isolated high surrogate. The strict decoder rejects an invalid UTF-8 sequence. This prevents malformed input from silently becoming replacement characters when exact data matters. Applications that intentionally replace damaged text can choose replacement fallback instead, but that is a different data-loss policy.

Define framing and normalization separately

Encoding does not add a message boundary. If a protocol sends a byte length, calculate it from the encoded bytes rather than text.Length. A receiver that reads a stream in arbitrary chunks must also handle characters split across chunks. Use a Decoder or a correctly configured StreamReader instead of decoding each byte buffer as an independent complete string.

The first constructor argument controls the UTF-8 preamble returned by GetPreamble. GetBytes does not automatically prefix that preamble. Decide whether the file format permits or requires a byte order mark. Do not add one to a protocol merely because a text editor uses it for some files.

Normalization is another independent choice. The last two lines show that visually similar text can have different byte representations. Form C normalization makes these particular strings equal, but it is not a universal identity rule for names, identifiers or passwords. Apply normalization only when the format or application contract specifies it, and apply the same rule on both sides before comparing or hashing.

Keep binary data binary

For binary payloads, use byte arrays or streams. Arbitrary bytes are not necessarily valid UTF-8. Converting them through a string and back can corrupt the data when a replacement fallback is involved. If a text-only format must carry bytes, use a reversible representation such as Base64 and identify it explicitly.

Test non-ASCII text, malformed input and a supplementary character. ASCII-only tests can pass even when producer and consumer disagree about encoding. A successful round trip under one encoder proves the sample's local conversion, not compatibility with a separate system using an unspecified encoding.

References

UTF8Encoding Constructor (System.Text)
Initializes a new instance of the UTF8Encoding class.
https://learn.microsoft.com/en-us/dotnet/api/system.text.utf8encoding.-ctor?view=net-10.0
Introduction to character encoding in .NET - .NET
Learn about character encoding and decoding in .NET.
https://learn.microsoft.com/en-us/dotnet/standard/base-types/character-encoding-introduction
String.Normalize Method (System)
Returns a new string whose binary representation is in a particular Unicode normalization form.
https://learn.microsoft.com/en-us/dotnet/api/system.string.normalize?view=net-10.0

Question provenance

This article addresses How do I get a consistent byte representation of strings in C# without manually specifying an encoding? , asked by Agnel Kurian on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored for current .NET. No answer text or code is reproduced.

Author: Herman Schoenfeld