Skip to content

OnixLabs.Core.Collections.Generic.IEqualityComparerExtensions

matthew edited this page May 27, 2026 · 1 revision

IEqualityComparerExtensions Class

Provides extension methods for IEqualityComparer<T> instances, supplying a convenience extension over a possibly-null comparer.

Namespace OnixLabs.Core.Collections.Generic
Assembly OnixLabs.Core.dll (NuGet)
Inheritance object → IEqualityComparerExtensions

Definition

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

Note IEqualityComparerExtensions is marked [EditorBrowsable(EditorBrowsableState.Never)], so it is hidden from IntelliSense completion lists even though it is public. Its extension method GetOrDefault is still fully usable on any IEqualityComparer<T>? receiver after adding using OnixLabs.Core.Collections.Generic;.

Remarks

The extension operates over an IEqualityComparer<T>? receiver, which may be null. It is used throughout the LINQ extensions in OnixLabs.Core.Linq to normalise an optional comparer argument: callers may pass null to mean "use the default comparer for the element type", and GetOrDefault resolves that to a concrete, non-null comparer.

The class uses a C# 14 extension block (extension<T>(IEqualityComparer<T>? receiver) { ... }), so the receiver type appears in the block declaration rather than as a this parameter. The call-site signature is the standard extension-method form shown below.

Examples

Normalising an optional comparer

using OnixLabs.Core.Collections.Generic;
using System.Collections.Generic;

IEqualityComparer<string>? maybeComparer = null;

// Resolves to EqualityComparer<string>.Default when null.
IEqualityComparer<string> comparer = maybeComparer.GetOrDefault();
bool equal = comparer.Equals("a", "a"); // True

Passing an optional comparer to a helper

using OnixLabs.Core.Collections.Generic;
using System.Collections.Generic;

static bool ContainsItem<T>(IEnumerable<T> source, T item, IEqualityComparer<T>? comparer = null)
{
    IEqualityComparer<T> resolved = comparer.GetOrDefault();
    foreach (T element in source)
        if (resolved.Equals(element, item)) return true;
    return false;
}

Methods

Method Returns Description
GetOrDefault<T>() IEqualityComparer<T> Gets the current comparer, or the default comparer when it is null.

GetOrDefault()

public IEqualityComparer<T> GetOrDefault()

Gets the current IEqualityComparer<T>, or the default comparer (EqualityComparer<T>.Default) if the current comparer is null.

Type Parameter Description
T The underlying type of the current IEqualityComparer<T> instance.

Returns — The current IEqualityComparer<T>, or EqualityComparer<T>.Default if the current comparer is null.

See Also

ONIXLabs .NET Library


Clone this wiki locally