C# Reference · Strings and Text
The Encoding class
Reference for System.Text.Encoding in C#: convert strings to bytes and back with UTF-8, UTF-16, ASCII and Latin1, count bytes, and handle invalid data.
A .NET string is a sequence of UTF-16 code units. Files, sockets and HTTP bodies carry bytes. System.Text.Encoding is the bridge: it turns text into bytes (GetBytes) and bytes back into text (GetString) using one agreed set of rules, such as UTF-8 or UTF-16.
Use UTF-8 unless a format forces something else. Encoding.UTF8 is a ready-made instance, and Encoding.Unicode is UTF-16 little-endian. If you pick the wrong encoding when reading, you get garbled text or replacement characters, not an exception, so always write and read with the same one.
byte[] bytes = Encoding.UTF8.GetBytes("héllo"); string text = Encoding.UTF8.GetString(bytes);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public abstract class Encoding { public static Encoding UTF8 { get; } public static Encoding Unicode { get; } // UTF-16 LE public static Encoding BigEndianUnicode { get; } public static Encoding UTF32 { get; } public static Encoding Latin1 { get; } public static Encoding ASCII { get; } public virtual byte[] GetBytes(string s); public virtual int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes); public virtual string GetString(byte[] bytes); public virtual string GetString(ReadOnlySpan<byte> bytes); public virtual int GetByteCount(string s); public virtual int GetMaxByteCount(int charCount); public static Encoding GetEncoding(string name); }
| Name | Description |
|---|---|
s / chars |
The text to encode. |
bytes |
The data to decode, or the destination buffer for the span overloads. |
charCount |
Number of UTF-16 code units, for the worst-case size estimate. |
Returns: GetBytes returns a new array (or the number of bytes written for the span overload). GetString returns the decoded text. GetByteCount returns the exact size without allocating.
Errors / undefined behavior: ArgumentNullException for a null string or array. The span overload of GetBytes throws ArgumentException if the destination is too small. Invalid data never throws with the built-in instances: they use replacement fallbacks (U+FFFD when decoding, ? for ASCII encoding).
Usage notes
- UTF-8 is the default for new code.
File.ReadAllText,StreamWriterandHttpClientalready use it, so you rarely needEncodingby hand except for sockets, hashing and binary formats. - Byte counts differ. In UTF-8, ASCII characters take 1 byte, accented Latin letters 2, most other scripts 3 and emoji 4. Use
GetByteCountto measure;s.Lengthcounts UTF-16 units, not bytes. - ASCII and Latin1 lose data.
Encoding.ASCIIturns every character above U+007F into?, and Latin1 does so above U+00FF. The euro sign in the example does not survive either one. - Replacement characters are a symptom. Seeing U+FFFD (
�) means bytes were decoded with the wrong encoding or were cut in the middle of a multi-byte sequence. - Byte order mark.
GetBytesnever adds a BOM. The three-byte UTF-8 preamble is only written by stream classes that are given an encoding with a preamble, such as aStreamWritercreated withEncoding.UTF8. CheckPreamble(3 bytes here) if a consumer chokes on extra bytes at the start;new UTF8Encoding(false)has none. - Streaming needs a decoder. When bytes arrive in chunks, a multi-byte character can be split between chunks. Use
encoding.GetDecoder()(orStreamReader), which remembers the unfinished bytes. - Legacy code pages. Encodings such as Windows-1252 need
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance)first. Prefer UTF-8 for anything you control. - Performance. Prefer the
Spanoverloads andGetByteCountplus a pooled buffer when encoding in hot paths; they avoid allocating an array per call.