Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we use ICollection<T> in the Interface and Collection<T> in the class?

Tags:

c#

collections

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?

like image 926
DarkNightFan Avatar asked Nov 04 '22 18:11

DarkNightFan


1 Answers

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.

like image 187
Sergey Kalinichenko Avatar answered Nov 12 '22 19:11

Sergey Kalinichenko