Skip to content

Instantly share code, notes, and snippets.

@jnm2
Created August 24, 2019 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnm2/b3f8c899048ca614c2626ec2df0f9a0c to your computer and use it in GitHub Desktop.
Save jnm2/b3f8c899048ca614c2626ec2df0f9a0c to your computer and use it in GitHub Desktop.
using System;
using System.Collections;
using System.Collections.Generic;
public static class CommonUtils
{
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="enumerable"/> is <see langword="null"/>.
/// </exception>
public static bool TryGetCollectionCount<T>(IEnumerable<T> enumerable, out int count)
{
switch (enumerable)
{
case null:
throw new ArgumentNullException(nameof(enumerable));
case IReadOnlyCollection<T> collection:
count = collection.Count;
return true;
case ICollection<T> collection:
count = collection.Count;
return true;
case ICollection collection:
count = collection.Count;
return true;
default:
count = default;
return false;
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
public static class TryGetCollectionCountTests
{
[Test]
public static void Detects_size_of_IReadOnlyCollection()
{
var collection = Substitute.For<IReadOnlyCollection<int>>();
collection.Count.Returns(42);
CommonUtils.TryGetCollectionCount(collection, out var count).ShouldBeTrue();
count.ShouldBe(42);
collection.ReceivedCalls().ShouldHaveSingleItem();
}
[Test]
public static void Detects_size_of_generic_ICollection()
{
var collection = Substitute.For<ICollection<int>>();
collection.Count.Returns(42);
CommonUtils.TryGetCollectionCount(collection, out var count).ShouldBeTrue();
count.ShouldBe(42);
collection.ReceivedCalls().ShouldHaveSingleItem();
}
[Test]
public static void Detects_size_of_nongeneric_ICollection()
{
var collection = Substitute.For<ICollection, IEnumerable<int>>();
collection.Count.Returns(42);
CommonUtils.TryGetCollectionCount((IEnumerable<int>)collection, out var count).ShouldBeTrue();
count.ShouldBe(42);
collection.ReceivedCalls().ShouldHaveSingleItem();
}
[Test]
public static void Does_not_detect_size_of_non_collection_enumerable()
{
var collection = Substitute.For<IEnumerable<int>>();
CommonUtils.TryGetCollectionCount(collection, out _).ShouldBeFalse();
collection.ReceivedCalls().ShouldBeEmpty();
}
[Test]
public static void Null_is_not_allowed()
{
var ex = Should.Throw<ArgumentNullException>(() =>
CommonUtils.TryGetCollectionCount<int>(enumerable: null, count: out _));
ex.ParamName.ShouldBe("enumerable");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment