Encoding.UTF8.GetString includes BOM in output string
05:53 07 Jul 2023

Consider this code

using var mem = new MemoryStream();
await using var writer = new StreamWriter(mem, Encoding.UTF8);

await writer.WriteLineAsync("Test");
await writer.FlushAsync();
mem.Position = 0;

Then this code throws

var x = Encoding.UTF8.GetString(mem.ToArray());
if (x[0] != 'T') throw new Exception("Bom is present in string");

Becaus BOM is present. Which doesnt make sense since GetString should decode the stream to decoded string.

This code works as intended and does not include the BOM

using var reader = new StreamReader(mem, Encoding.UTF8);
var x = await reader.ReadToEndAsync();
if (x[0] != 'T') throw new Exception("Bom is present in string");

Anyone know Microsofts reasoning about this? To me it seems strange to keep a BOM in a method called GetString.

c# encoding byte-order-mark