Search code examples
c#collectionsnunitienumerabletest-coverage

concrete implemantation of IEnumerable<T> that is not ICollection<T>


I would like to know if any of the classes in the .net framework that implement IEnumerable doesn't implement the ICollection interface.

I'm asking it because I can't get 100% code coverage in the following extension method that I wrote:

public static int GetSafeCount<T>(this IEnumerable<T> nullableCollaction)
    {
        if (nullableCollaction == null)
        {
            return 0;
        }
        var collection = nullableCollaction as ICollection<T>;
        if (collection != null)
        {
            return collection.Count;
        }
        return nullableCollaction.Count();
    }

The last line is not covered in any of my tests and I can't find the correct class to instantiate in order to cover it.

my test code is:

[Test]
    public void GetSafeCount_NullObject_Return0()
    {
        IEnumerable<string> enumerable=null;

        Assert.AreEqual(0, enumerable.GetSafeCount());
    }
    [Test]
    public void GetSafeCount_NonICollectionObject_ReturnCount()
    {
        IEnumerable<string> enumerable = new string[]{};

        Assert.AreEqual(0, enumerable.GetSafeCount());
    }

Solution

  • You can use the Stack<T> class, it implements ICollection and IEnumerable<T> but not ICollection<T>.

    Here is how the class is defined:

    public class Stack<T> : IEnumerable<T>, IEnumerable, ICollection, 
        IReadOnlyCollection<T>