using System.Globalization;
using System.Runtime.CompilerServices;
public sealed class ExampleCustomFormatter: IFormatProvider, ICustomFormatter
public object? GetFormat(Type? formatType) => formatType == typeof(ICustomFormatter) ? this : null;
public string Format(string? format, object? arg, IFormatProvider? formatProvider) => format == "S" && arg is byte[] i ? Convert.ToBase64String(i) : arg is IFormattable formattable ? formattable.ToString(format, formatProvider) : arg?.ToString() ?? string.Empty;
public static class StringExtensions
public static string FormatString(byte[] buffer) => string.Create(new ExampleCustomFormatter(), stackalloc char[64], $"{buffer:S}");
[InterpolatedStringHandler]
public ref struct BinaryMessageInterpolatedStringHandler
private readonly DefaultInterpolatedStringHandler handler;
public BinaryMessageInterpolatedStringHandler(int literalLength, int formattedCount, bool predicate, out bool handlerIsValid)
handler = new DefaultInterpolatedStringHandler(literalLength, formattedCount);
public void AppendLiteral(string s) => handler.AppendLiteral(s);
public void AppendFormatted<T>(T t) => handler.AppendFormatted(t);
public override string ToString() => handler.ToStringAndClear();
public static void Main()
byte[] test1 = new byte[1] { 0x55 };
ReadOnlySpan<byte> test2 = new byte[1] { 0x55 };
Console.WriteLine($"{test1:S}");
Console.WriteLine(StringExtensions.FormatString(test1));