Skip to content

OnixLabs.Core.Text.EncodingExtensions

matthew edited this page May 27, 2026 · 1 revision

EncodingExtensions Class

Provides extension methods for Encoding instances. These methods are exposed through a C# 14 extension block over a receiver of type Encoding?, so they may be invoked even when the receiver is null.

Namespace OnixLabs.Core.Text
Assembly OnixLabs.Core.dll (NuGet)
Inheritance object → EncodingExtensions

Definition

[EditorBrowsable(EditorBrowsableState.Never)]
public static class EncodingExtensions

Note This class is decorated with [EditorBrowsable(EditorBrowsableState.Never)], which hides it from IntelliSense completion lists in some IDE configurations. The extension methods remain fully public and callable; they primarily support the Base value codecs and other internal text formatting throughout the library.

Remarks

EncodingExtensions adds null-safe convenience methods over Encoding? receivers. Because the class uses a C# 14 extension(Encoding? receiver) block, all methods are accessible on any Encoding variable regardless of whether its value is null. The GetOrDefault() method acts as the null-coalescing pivot, and all other methods call through it so the caller never needs to guard against a null encoding.

Bring the methods into scope with:

using OnixLabs.Core.Text;

Methods

Method Returns Description
GetOrDefault() Encoding Gets the current encoding, or Encoding.UTF8 if the receiver is null.
GetBytes(ReadOnlySpan<char>) byte[] Obtains a byte array from the specified character span using the current or default encoding.

GetOrDefault()

public Encoding GetOrDefault()

Gets the current Encoding, or the default encoding if the current Encoding is null. The default encoding is Encoding.UTF8.

Returns — The receiving Encoding, or Encoding.UTF8 when the receiver is null.

using OnixLabs.Core.Text;
using System.Text;

Encoding? maybeNull = null;
Encoding encoding = maybeNull.GetOrDefault(); // Encoding.UTF8

Encoding ascii = Encoding.ASCII.GetOrDefault(); // Encoding.ASCII

GetBytes(ReadOnlySpan<char>)

public byte[] GetBytes(ReadOnlySpan<char> value)

Obtains a byte array from the specified ReadOnlySpan<char> instance, encoding the characters using the receiving Encoding, or Encoding.UTF8 when the receiver is null (see GetOrDefault()).

Parameter Type Description
value ReadOnlySpan<char> The value from which to obtain a byte array.

Returns — A byte array containing the encoded representation of value.

using OnixLabs.Core.Text;
using System.Text;

byte[] utf8 = Encoding.UTF8.GetBytes("ABC");   // [ 0x41, 0x42, 0x43 ]

Encoding? fallback = null;
byte[] viaDefault = fallback.GetBytes("ABC");  // encoded as UTF-8

See Also

ONIXLabs .NET Library


Clone this wiki locally