0

Is it possible to permit only some specific classes to implement an iterface?

For Exmaple:

In System.Collections.Generic.Dictionary class has KeyCollection sealed class with implemented System.Collections.Generic.ICollection<TKey> as well System.Collections.ICollection but when I look at code Visual Studio builds from metadata it shows that KeyCollection implements only System.Collections.ICollection interface methods.

How to restrict same?

enter image description here

Simple example: I have used the same interfaces but i have faced the compilation issue.

enter image description here

yoganathan k
  • 213
  • 4
  • 16
  • 1
    How is that an example of what you're asking for, if anyone can implement `ICollection` or `ICollection`? –  Dec 05 '16 at 05:50
  • If you want restrict implementation of interface - move interface in the own assembly(project), make interface `internal`, in the same assembly implement interface in the public classes, which you will use in your other projects – Fabio Dec 05 '16 at 05:52
  • No you can't, how one can restrict class from not implementing any interface implemented on it. – A.T. Dec 05 '16 at 05:52
  • 1
    Why do you want to do this? Most likely you keeping some use-case in mind. – Dennis Dec 05 '16 at 05:57
  • In above case ICollection and ICollection interfaces are used but ICollection interface only implemented how is it possible? – yoganathan k Dec 05 '16 at 06:03
  • @yoganathank implicit vs. explicit - http://stackoverflow.com/questions/143405/c-sharp-interfaces-implicit-implementation-versus-explicit-implementation ? (Clearly it has nothing to do with what you are *asking* in the post... also it may be what you *actually interested in*). – Alexei Levenkov Dec 05 '16 at 06:18
  • Also please confirm that my edit of the post is inline with what you see (in particular that you've used VS autogenerated code from metadata to capture picture) – Alexei Levenkov Dec 05 '16 at 06:22

1 Answers1

0

That is true but KeyCollection hasn't any restriction. KeyCollection seems to be using ICollection and ICollection<TKey> methods. Actually, it implements all methods. Beacuse ICollection<TKey> and ICollection implement IEnumerable<T>, IEnumerable interfaces.

ICollection<T> : IEnumerable<T>, IEnumerable

ICollection : IEnumerable

mfatih
  • 476
  • 4
  • 10