Friday, November 15, 2019

c# - Should we use ICollection in the Interface and Collection in the class?



I have an interface and a class that implements it. Now I want to keep a collection of some things in this class.
Sholud I use ICollection in its interface part and use Collection in the concerete class part?



Is it a better practice and more flexible to use ICollection in both parts?



Also: the "things" that I said I want to keep a collection of them in my class, they are also objects of some other classes I have and those classes again have their own interfacs. So what is the best pracitce? should I even use the interface type of these clases when I want to save them in the collection?


Answer




If you can expose an interface rather than a class, expose the interface; expose the class only if you must do so, for example, to expose methods not available on the interface. You should do it both in your interface and in your class.



The rationale is that information hiding is a "good thing", so if you can do it without losing of generality, you should do so.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...