.NET API Documentation

Home

System.Text.Encoder

Namespace: System.Text

Assembly: System.Runtime.dll

Summary

Converts a sequence of Unicode characters into a sequence of bytes. The Encoder class provides functionality to convert characters to bytes while preserving state between conversions, allowing for correct handling of characters that span multiple calls (for example, UTF-8 multi‑byte sequences).

Inheritance

Members

Methods

SignatureDescription
int GetByteCount(char[] chars, int index, int count, bool flush) Calculates the number of bytes produced by encoding a set of characters.
int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) Encodes a set of characters into a byte array.
void Reset() Resets any internal state stored by the encoder.
bool MustFlush { get; } Indicates whether the encoder must flush its state after encoding.
int GetByteCount(char* chars, int count, bool flush) Unsafe overload that calculates byte count from a pointer.
int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) Unsafe overload that encodes characters pointed to by chars into bytes pointed to by bytes.

Properties

SignatureDescription
bool IsSingleByte { get; } Indicates whether the encoder produces a single byte per character.
EncoderFallback Fallback { get; set; } Gets or sets the fallback mechanism used for characters that cannot be encoded.

Example

Encoding a string to UTF‑8 bytes while handling characters that may require multiple calls:

using System;
using System.Text;

class Program
{
    static void Main()
    {
        string text = "Hello 🌍! こんにちは";
        Encoder encoder = Encoding.UTF8.GetEncoder();

        char[] chars = text.ToCharArray();
        byte[] buffer = new byte[encoder.GetByteCount(chars, 0, chars.Length, true)];

        int bytesEncoded = encoder.GetBytes(chars, 0, chars.Length, buffer, 0, true);
        Console.WriteLine($"\"{text}\" encoded to {bytesEncoded} bytes.");
        Console.WriteLine(BitConverter.ToString(buffer));
    }
}

Related Topics