Codectionary / Developer documentation / C#

Encode and Decode UTF-8 Deliberately

Convert between strings and bytes while choosing how invalid input should be handled.

Read the syntax

Convert between strings and bytes while choosing how invalid input should be handled.

GetBytes returns five bytes without adding a preamble.

What it is and why to use it

A string is text in memory; a byte array is encoded data. Network protocols and files need an agreed encoding so both sides interpret the same bytes. UTF-8 is a variable-length Unicode encoding, not a guarantee that every character occupies one byte. Encoding is also different from encryption or HTML escaping.

How it works

GetBytes encodes text and GetString decodes bytes. Encoding.UTF8 normally uses replacement behaviour for invalid sequences. A UTF8Encoding instance with throwOnInvalidBytes set to true can reject invalid data with an exception. The encoderShouldEmitUTF8Identifier option controls the preamble returned by GetPreamble; GetBytes does not automatically prepend that preamble.

Common mistakes and limitations

Do not guess an encoding for data whose format specifies one. Do not truncate arbitrary encoded bytes and expect a complete character. A BOM/preamble is not required by every UTF-8 format. Decide whether replacing malformed input is acceptable or whether the boundary must reject it.

Run the examples locally

These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.

Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.

C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.

Create and enter a project

dotnet new console -n CSharpExample --framework net10.0
cd CSharpExample

CSharpExample.csproj settings used for these examples

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>12.0</LangVersion>
    <Nullable>enable</Nullable>
    <ImplicitUsings>disable</ImplicitUsings>
  </PropertyGroup>
</Project>

Build and run after saving one example in Program.cs

dotnet build
dotnet run --no-build

Continue learning

Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.

Syntax

var utf8 = new UTF8Encoding(false, true);
byte[] bytes = utf8.GetBytes(text);

Examples

Round-trip a short string

Count the UTF-8 bytes and decode them using the same encoding.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Text;

var utf8 = new UTF8Encoding(false, true);
byte[] bytes = utf8.GetBytes("café");
Console.WriteLine(bytes.Length);
Console.WriteLine(utf8.GetString(bytes));
  1. The first three ASCII letters use one byte each and é uses two in UTF-8.
  2. GetBytes returns five bytes without adding a preamble.
  3. Decoding with the same encoding restores the text. This is a round trip, not encryption.
  4. Expected output: 5 café
  5. Specify encoding at file and network boundaries.

Reject an invalid UTF-8 byte sequence

Use strict decoding at a controlled input boundary.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Text;

var utf8 = new UTF8Encoding(false, true);
try {
    Console.WriteLine(utf8.GetString(new byte[] { 0xC3, 0x28 }));
} catch (DecoderFallbackException) {
    Console.WriteLine("Invalid UTF-8");
}
  1. 0xC3 begins a two-byte UTF-8 sequence, but 0x28 is not a valid continuation byte.
  2. The strict decoder throws instead of silently inserting replacement text.
  3. The catch converts this known validation failure into a controlled message. Real applications should choose an appropriate reject/log policy without exposing sensitive input.
  4. Expected output: Invalid UTF-8
  5. Specify encoding at file and network boundaries.

Best practices

  • Specify encoding at file and network boundaries.
  • Choose replacement or rejection of malformed data deliberately.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading