ICollection vs ICollection<T>- Ambiguity between ICollection<T>.Count and ICollection.Count

StackOverflow https://stackoverflow.com/questions/1552456

  •  20-09-2019
  •  | 
  •  

Question

Note: This is similar, but not quite the same as this other question

I've implemented an IBusinessCollection interface. It dervies from both ICollection<T>, and the old-busted non-generic ICollection. I'd prefer to just dump the old busted ICollection, but I'm using WPF databinding with a CollectionView which wants me to implement the old-busted non-generic IList :-(

Anyway, the interfaces look like this:

public interface IBusinessCollection<T> : ICollection<T>, ICollection
{ }

public interface ICollection<T>
{ int Count { get; } }

public interface ICollection
{ int Count { get; } }

Due to using Dependency Injection, I'm passing around objects of type IBusinessCollection<T> using their interfaces, not by concrete types, so I have something like this:

internal class AnonymousCollection : IBusinessCollection<string>
{ 
    public int Count { get { return 5; } }
}

public class Factory
{
    public static IBusinessCollection<string> Get()
    { return new AnonymousCollection(); }
}

When I try and call this code, I get an error, as follows:

var counter = Factory.Get();
counter.Count; // Won't compile
// Ambiguity between 'ICollection<string>.Count' and 'ICollection.Count'

There are 3 ways to make this compile, but all of them are ugly.

  1. Cast the class to it's concrete implementation (which I may not know)

  2. Cast the class explicitly to ICollection

  3. Cast the class explicitly to ICollection<T>

Is there a fourth option which doesn't require me to cast things at all? I can make whatever changes I need to IBusinessCollection<T>

Was it helpful?

Solution

This appears to solve the issues in my quick tests.

public interface IBusinessCollection<T> : ICollection<T>, ICollection
{
    new int Count { get;  }
}

OTHER TIPS

ICollection<string> counter = Factory.Get();
counter.Count; // No longer ambiguous
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top