Question

I'mm building a WPF app with MVVM and am using ObservableCollection. While working on my ViewModel, I decided to inspect the type definition of the ObservableCollection and I saw something that I thought was odd:

// class definition for ObservableCollection
ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
// derives from Collection<T>
... 
// class definition for Collection<T>
Collection<T> : IList<T>, ICollection<T>, IEnumerable<T> ... (as well as non-generics)

Now, here's the question:

If ICollection<T> implements IEnumerable<T> 
AND 
IList<T> implements ICollection<T> AS WELL AS IEnumerable<T>
...
...
Why does Collection<T> implement ALL THREE?

Is this really how its implemented or is this VS2010 playing tricks on me?

Was it helpful?

Solution

If a class, say Collection<T> implements IList<T>, and you would go to the definition in Visual Studio, it will show you all interfaces that Collection<T> implements. If Collection<T> implements IList<T>, it will also implement ICollection<T> and IEnumerable because

IList<T> : ICollection<T>

and

ICollection<T> : IEnumerable<T>

etc.

In otherwords, if I write

interface IFoo : IBar, IBaz {}
interface IBar {}
interface IBaz {}

class Foobar : IFoo {}

Then Visual Studio will give me:

Foobar : IFoo, IBar, IBaz {...} (from metadata).

If I implement IFoo, I must also implement IBar because IFoo extends IBar, thus it makes sense to show that Foobar also implement IBar and IBaz (otherwise I'd only see IFoo, and would have to navigate to IFoo to see IBar etc.)

OTHER TIPS

Actually not only Visual Studio, but other tools (like Reflector) also will show all interfaces, which are implemented by type. I think this functionality is implemented via Type.GetInterfaces:

Type type = typeof(MyClass);
Type[] interfaces = type.GetInterfaces();

This method gets all the interfaces implemented or inherited by the current Type. Implemented interfaces are those, which are declared as a part of definition of the Type:

public class MyClass : IList<T>

But interfaces can inherit other interfaces. So interfaces, which are inherited by implemented interfaces, are inherited interfaces:

 public interface IList<T> : ICollection<T>

 public interface ICollection<T> : IEnumerable<T>

 public interface IEnumerable<T> : IEnumerable

So, here we have three inherited interfaces and one implemented. All are considered as type interfaces.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top