Why does this interface have to be explicitly implemented?

  • A+
Category:Languages

Coming back to C# after a few years so I'm a little rusty. Came across this (simplified) code and it's leaving my head scratching.

Why do you have to explicitly implement the IDataItem.Children property? Doesn't the normal Children property satisfy the requirement? After all, the property is used directly to satisfy it. Why is it not implicit?

public interface IDataItem {      IEnumerable<string> Children { get; } }  public class DataItem : IDataItem {      public Collection<string> Children { get; } = new Collection<string>();      // Why doesn't 'Children' above implement this automatically?!     // After all it's used directly to satisfy the requirement!     IEnumerable<string> IDataItem.Children => Children; } 

According to the C# source, here's the definition of Collection<T>:

[System.Runtime.InteropServices.ComVisible(false)] public class Collection<T> :     System.Collections.Generic.ICollection<T>,     System.Collections.Generic.IEnumerable<T>, <-- Right Here     System.Collections.Generic.IList<T>,     System.Collections.Generic.IReadOnlyCollection<T>,     System.Collections.Generic.IReadOnlyList<T>,     System.Collections.IList 

As you can see, it explicitly implements IEnumerable<T> and from my understanding, if 'X' implements 'Y' then 'X' is a 'Y', so Collection<String> is an IEnumerable<String> so I'm not sure why it isn't satisfied.

 


In your example your "normal" Children property do not actually satisfy the interface requirement. The type is different. It does not really matter that you can cast it - they are different.

Similar example and maybe a bit more obvious is if you would implement an interface with a actual method that returns IEnumerable and tried an ICollection method from the actual class. There is still that compile time error.

As @Ben Voigt said the conversion still generates some code, and if you want to have it - you need to add it implicitly.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: