CommunityToolkit / dotnet

.NET Community Toolkit is a collection of helpers and APIs that work for all .NET developers and are agnostic of any specific UI platform. The toolkit is maintained and published by Microsoft, and part of the .NET Foundation.
https://docs.microsoft.com/dotnet/communitytoolkit/?WT.mc_id=dotnet-0000-bramin
Other
2.81k stars 279 forks source link

Guard add support System.Collections.Immutable #414

Open kronic opened 1 year ago

kronic commented 1 year ago

Overview

Guard IsNotEmpty not support ImmutableArray

API breakdown

namespace CommunityToolkit.Diagnostics;

partial class Guard
{
public static void IsNotEmpty<T>(ImmutableArray<T> collection, [CallerArgumentExpression("collection")] string name = "")
public static void IsNotEmpty<T>(ImmutableHashSet<T> collection, [CallerArgumentExpression("collection")] string name = "")
public static void IsNotEmpty<T>(ImmutableList<T> collection, [CallerArgumentExpression("collection")] string name = "")
public static void IsNotEmpty<T>(ImmutableQueue<T> collection, [CallerArgumentExpression("collection")] string name = "")
public static void IsNotEmpty<T>(ImmutableSortedSet<T> collection, [CallerArgumentExpression("collection")] string name = "")
public static void IsNotEmpty<T>(ImmutableStack<T> collection, [CallerArgumentExpression("collection")] string name = "")

public static void IsNotEmpty<TKey, TValue>(ImmutableDictionary<TKey, TValue> collection, 
[CallerArgumentExpression("collection")] string name = "") where TKey : notnull
}
public static void IsNotEmpty<TKey, TValue>(ImmutableSortedDictionary<TKey, TValue> collection, 
[CallerArgumentExpression("collection")] string name = "") where TKey : notnull
}

Usage example

using CommunityToolkit.Diagnostics;

public class Foo
{
    public void Test(ImmutableArray<string> values)
    {
        Guard.IsNotEmpty(values);
    }
}

Breaking change?

No

Alternatives

no

Additional context

No response

Help us help you

Yes, I'd like to be assigned to work on this item

ovska commented 1 year ago

Seems reasonable to me, perhaps support could be added for ArraySegment<> as well to avoid boxing? Both of these can be worked around by casting to Span/Memory, but you lose the benefits of CallerArgumentExpression at the same time.

Workaround for now could be using Guard.IsGreaterThan(immutableArray.Length, 0), which causes a somewhat useful error: System.ArgumentOutOfRangeException: Parameter "immutableArray.Length" (int) must be greater than <0>, was <0>.

This is probably not a breaking change as using ImmutableArray as-is currently errors due to ambiguous invocation between two interfaces.