Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,47 @@ public static void CallerArgumentExpression()
act.Should().Throw<ArgumentOutOfRangeException>()
.WithParameterName(nameof(testArray));
}

[Fact]
public static void DefaultImmutableArrayInRange()
{
var defaultArray = default(ImmutableArray<int>);

var result = defaultArray.MustHaveLengthIn(Range.FromInclusive(0).ToInclusive(5));

result.IsDefault.Should().BeTrue();
}

[Fact]
public static void DefaultImmutableArrayNotInRange()
{
var defaultArray = default(ImmutableArray<int>);

var act = () => defaultArray.MustHaveLengthIn(Range.FromInclusive(1).ToInclusive(5), nameof(defaultArray));

act.Should().Throw<ArgumentOutOfRangeException>()
.And.Message.Should().Contain("must have its length in between 1 (inclusive) and 5 (inclusive)")
.And.Contain("has no length because it is the default instance");
}

[Fact]
public static void DefaultImmutableArrayCustomException()
{
var defaultArray = default(ImmutableArray<int>);

Test.CustomException(
defaultArray,
Range.FromInclusive(1).ToInclusive(5),
(array, r, exceptionFactory) => array.MustHaveLengthIn(r, exceptionFactory)
);
}

[Fact]
public static void DefaultImmutableArrayCustomMessage() =>
Test.CustomMessage<ArgumentOutOfRangeException>(
message => default(ImmutableArray<int>).MustHaveLengthIn(
Range.FromInclusive(1).ToInclusive(5),
message: message
)
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
using System;
using System.Collections.Immutable;
using FluentAssertions;
using Light.GuardClauses.Exceptions;
using Xunit;

namespace Light.GuardClauses.Tests.CollectionAssertions;

public static class MustHaveMaximumLengthTests
{
[Theory]
[InlineData(new[] { 1, 2, 3, 4 }, 3)]
[InlineData(new[] { 1, 2 }, 1)]
[InlineData(new[] { 500 }, 0)]
public static void ImmutableArrayMoreItems(int[] items, int length)
{
var immutableArray = items.ToImmutableArray();
Action act = () => immutableArray.MustHaveMaximumLength(length, nameof(immutableArray));

var assertion = act.Should().Throw<InvalidCollectionCountException>().Which;
assertion.Message.Should().Contain(
$"{nameof(immutableArray)} must have at most count {length}, but it actually has count {immutableArray.Length}."
);
assertion.ParamName.Should().BeSameAs(nameof(immutableArray));
}

[Theory]
[InlineData(new[] { "Foo" }, 1)]
[InlineData(new[] { "Bar" }, 2)]
[InlineData(new[] { "Baz", "Qux", "Quux" }, 5)]
public static void ImmutableArrayLessOrEqualItems(string[] items, int length)
{
var immutableArray = items.ToImmutableArray();
var result = immutableArray.MustHaveMaximumLength(length);
result.Should().Equal(immutableArray);
}

[Fact]
public static void ImmutableArrayEmpty()
{
var emptyArray = ImmutableArray<int>.Empty;
var result = emptyArray.MustHaveMaximumLength(5);
result.Should().Equal(emptyArray);
}

[Theory]
[InlineData(new[] { 87, 89, 99 }, 1)]
[InlineData(new[] { 1, 2, 3 }, -30)]
public static void ImmutableArrayCustomException(int[] items, int maximumLength)
{
var immutableArray = items.ToImmutableArray();

Action act = () => immutableArray.MustHaveMaximumLength(
maximumLength,
(array, length) => new ($"Custom exception for array with length {array.Length} and max {length}")
);

act.Should().Throw<Exception>()
.WithMessage($"Custom exception for array with length {immutableArray.Length} and max {maximumLength}");
}

[Fact]
public static void ImmutableArrayNoCustomExceptionThrown()
{
var immutableArray = new[] { "Foo", "Bar" }.ToImmutableArray();
var result = immutableArray.MustHaveMaximumLength(2, (_, _) => new ());
result.Should().Equal(immutableArray);
}

[Fact]
public static void ImmutableArrayCustomMessage()
{
var immutableArray = new[] { 1, 2, 3 }.ToImmutableArray();

Test.CustomMessage<InvalidCollectionCountException>(
message => immutableArray.MustHaveMaximumLength(2, message: message)
);
}

[Fact]
public static void ImmutableArrayCallerArgumentExpression()
{
var myImmutableArray = new[] { 1, 2, 3 }.ToImmutableArray();

var act = () => myImmutableArray.MustHaveMaximumLength(2);

act.Should().Throw<InvalidCollectionCountException>()
.WithParameterName(nameof(myImmutableArray));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -140,4 +140,51 @@ public static void ImmutableArrayCallerArgumentExpression()
act.Should().Throw<ExistingItemException>()
.WithParameterName(nameof(array));
}

[Fact]
public static void ImmutableArrayDefaultInstanceDoesNotContainItem()
{
var defaultArray = default(ImmutableArray<int>);

// Default instance should not throw for any item since it cannot contain anything
var result = defaultArray.MustNotContain(42);

result.IsDefault.Should().BeTrue();
}

[Fact]
public static void ImmutableArrayDefaultInstanceCustomException()
{
var defaultArray = default(ImmutableArray<string>);

// Default instance should not throw even with custom exception factory
var result = defaultArray.MustNotContain(
"test",
(_, _) => new InvalidOperationException("Should not be called")
);

result.IsDefault.Should().BeTrue();
}

[Fact]
public static void ImmutableArrayDefaultInstanceCustomMessage()
{
var defaultArray = default(ImmutableArray<object>);

// Default instance should not throw even with custom message
var result = defaultArray.MustNotContain(new object(), message: "Custom message");

result.IsDefault.Should().BeTrue();
}

[Fact]
public static void ImmutableArrayDefaultInstanceCallerArgumentExpression()
{
var defaultArray = default(ImmutableArray<char>);

// Default instance should not throw, so no exception to check parameter name
var result = defaultArray.MustNotContain('x');

result.IsDefault.Should().BeTrue();
}
}
6 changes: 4 additions & 2 deletions Code/Light.GuardClauses/Check.MustHaveLengthIn.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ public static ImmutableArray<T> MustHaveLengthIn<T>(
string? message = null
)
{
if (!range.IsValueWithinRange(parameter.Length))
var length = parameter.IsDefault ? 0 : parameter.Length;
if (!range.IsValueWithinRange(length))
{
Throw.ImmutableArrayLengthNotInRange(parameter, range, parameterName, message);
}
Expand All @@ -98,7 +99,8 @@ public static ImmutableArray<T> MustHaveLengthIn<T>(
Func<ImmutableArray<T>, Range<int>, Exception> exceptionFactory
)
{
if (!range.IsValueWithinRange(parameter.Length))
var length = parameter.IsDefault ? 0 : parameter.Length;
if (!range.IsValueWithinRange(length))
{
Throw.CustomException(exceptionFactory, parameter, range);
}
Expand Down
56 changes: 56 additions & 0 deletions Code/Light.GuardClauses/Check.MustHaveMaximumLength.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System;
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
using Light.GuardClauses.ExceptionFactory;
using Light.GuardClauses.Exceptions;

namespace Light.GuardClauses;

public static partial class Check
{
/// <summary>
/// Ensures that the <see cref="ImmutableArray{T}" /> has at most the specified length, or otherwise throws an <see cref="InvalidCollectionCountException" />.
/// </summary>
/// <param name="parameter">The <see cref="ImmutableArray{T}" /> to be checked.</param>
/// <param name="length">The maximum length the <see cref="ImmutableArray{T}" /> should have.</param>
/// <param name="parameterName">The name of the parameter (optional).</param>
/// <param name="message">The message that will be passed to the resulting exception (optional).</param>
/// <exception cref="InvalidCollectionCountException">Thrown when <paramref name="parameter" /> has more than the specified length.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ImmutableArray<T> MustHaveMaximumLength<T>(
this ImmutableArray<T> parameter,
int length,
[CallerArgumentExpression("parameter")] string? parameterName = null,
string? message = null
)
{
if (parameter.IsDefault && length < 0 || parameter.Length > length)

Copilot AI Jul 21, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The condition logic is incorrect. It should throw when parameter.IsDefault AND length < 0, OR when parameter.Length > length. However, the current condition will throw for default instances when length < 0, but default instances should be allowed for any non-negative maximum length. The condition should be: if ((parameter.IsDefault && length < 0) || (!parameter.IsDefault && parameter.Length > length))

Suggested change
if (parameter.IsDefault && length < 0 || parameter.Length > length)
if ((parameter.IsDefault && length < 0) || (!parameter.IsDefault && parameter.Length > length))

Copilot uses AI. Check for mistakes.
{
Throw.InvalidMaximumCollectionCount(parameter, length, parameterName, message);
}

return parameter;
}

/// <summary>
/// Ensures that the <see cref="ImmutableArray{T}" /> has at most the specified length, or otherwise throws your custom exception.
/// </summary>
/// <param name="parameter">The <see cref="ImmutableArray{T}" /> to be checked.</param>
/// <param name="length">The maximum length the <see cref="ImmutableArray{T}" /> should have.</param>
/// <param name="exceptionFactory">The delegate that creates your custom exception. <paramref name="parameter" /> and <paramref name="length" /> are passed to this delegate.</param>
/// <exception cref="Exception">Your custom exception thrown when <paramref name="parameter" /> has more than the specified length.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ImmutableArray<T> MustHaveMaximumLength<T>(
this ImmutableArray<T> parameter,
int length,
Func<ImmutableArray<T>, int, Exception> exceptionFactory
)
{
if (parameter.IsDefault && length < 0 || parameter.Length > length)
Comment thread
feO2x marked this conversation as resolved.
Outdated
{
Throw.CustomException(exceptionFactory, parameter, length);
}

return parameter;
}
}
10 changes: 8 additions & 2 deletions Code/Light.GuardClauses/Check.MustNotContain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,9 @@ public static string MustNotContain(
/// <param name="parameterName">The name of the parameter (optional).</param>
/// <param name="message">The message that will be passed to the resulting exception (optional).</param>
/// <exception cref="ExistingItemException">Thrown when <paramref name="parameter" /> contains <paramref name="item" />.</exception>
/// <remarks>
/// The default instance of <see cref="ImmutableArray{T}" /> cannot contain any items, so this method will not throw for default instances.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ImmutableArray<T> MustNotContain<T>(
this ImmutableArray<T> parameter,
Expand All @@ -215,7 +218,7 @@ public static ImmutableArray<T> MustNotContain<T>(
string? message = null
)
{
if (parameter.Contains(item))
if (!parameter.IsDefault && parameter.Contains(item))
{
Throw.ExistingItem(parameter, item, parameterName, message);
}
Expand All @@ -230,6 +233,9 @@ public static ImmutableArray<T> MustNotContain<T>(
/// <param name="item">The item that must not be part of the <see cref="ImmutableArray{T}" />.</param>
/// <param name="exceptionFactory">The delegate that creates your custom exception. <paramref name="parameter" /> and <paramref name="item" /> are passed to this delegate.</param>
/// <exception cref="Exception">Your custom exception thrown when <paramref name="parameter" /> contains <paramref name="item" />.</exception>
/// <remarks>
/// The default instance of <see cref="ImmutableArray{T}" /> cannot contain any items, so this method will not throw for default instances.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[ContractAnnotation("exceptionFactory:null => halt")]
public static ImmutableArray<T> MustNotContain<T>(
Expand All @@ -238,7 +244,7 @@ public static ImmutableArray<T> MustNotContain<T>(
Func<ImmutableArray<T>, T, Exception> exceptionFactory
)
{
if (parameter.Contains(item))
if (!parameter.IsDefault && parameter.Contains(item))
{
Throw.CustomException(exceptionFactory, parameter, item);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,6 @@ public static void ImmutableArrayLengthNotInRange<T>(
throw new ArgumentOutOfRangeException(
parameterName,
message ??
$"{parameterName ?? "The immutable array"} must have its length in between {range.CreateRangeDescriptionText("and")}, but it actually has length {parameter.Length}."
$"{parameterName ?? "The immutable array"} must have its length in between {range.CreateRangeDescriptionText("and")}, but it actually {(parameter.IsDefault ? "has no length because it is the default instance" : $"has length {parameter.Length}")}."
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Issue 120 - MustHaveMaximumLength for ImmutableArray

## Context

The .NET library Light.GuardClauses already has several assertions for collections. They often rely on `IEnumerable<T>` or `IEnumerable`. However, these assertions would result in `ImmutableArray<T>` being boxed - we want to avoid that by providing dedicated assertions for this type which avoids boxing. For this issue, we implement the `MustHaveMaximumLength` assertion for `ImmutableArray<T>`.

## Tasks for this issue

- [ ] The production code should be placed in the Light.GuardClauses project. There is no existing `Check.MustHaveMaximumLength.cs` file, but there is a `Check.MustHaveMaximumCount.cs` file. Create a new file called `Check.MustHaveMaximumLength.cs` in the root folder of the project.
- [ ] In this file, create several extension method overloads called `MustHaveMaximumLength` for `ImmutableArray<T>`. It should be placed in the class `Check` which is marked as `partial`.
- [ ] Each assertion in Light.GuardClauses has two overloads - the first one takes the optional `parameterName` and `message` arguments and throw the default exception. The actual exception is thrown in the `Throw` class - use the existing `Throw.InvalidMaximumCollectionCount` method which is located in `ExceptionFactory/Throw.InvalidMaximumCollectionCount.cs`.
- [ ] The other overload takes a delegate which allows the caller to provide their own custom exceptions. Use the existing `Throw.CustomException` method and pass the delegate, the erroneous `ImmutableArray<T>` instance and the maximum length.
- [ ] Use the `Length` property of `ImmutableArray<T>` instead of `Count` for performance and correctness.
- [ ] Create unit tests for both overloads. The corresponding tests should be placed in Light.GuardClauses.Tests project. There is an existing file 'CollectionAssertions/MustHaveMaximumCountTests.cs' but you need to create a new file 'CollectionAssertions/MustHaveMaximumLengthTests.cs' for length-related tests. Please follow conventions of the existing tests (e.g. use FluentAssertions' `Should()` for assertions).

## Notes

- There are already plenty of other assertions and tests in this library. All overloads are placed in the same file in the production code project. The test projects has top-level folders for different groups of assertions, like `CollectionAssertions`, `StringAssertions`, `DateTimeAssertions` and so on. Please take a look at them to follow a similar structure and code style.
- This assertion specifically targets `ImmutableArray<T>` to avoid boxing that would occur with generic `IEnumerable<T>` extensions.
- Use the `Length` property instead of `Count` as this is the appropriate property for `ImmutableArray<T>`.
- The assertion should verify that the `ImmutableArray<T>` does not exceed the specified maximum length.
- If you have any questions or suggestions, please ask me about them.