Monday 6 May 2019

c# - Question regarding return types with collections



In my BL (will be a public API), I am using ICollection as the return types in my Find methods, like:



public static ICollection FindCustomers()
{
Collection customers = DAL.GetCustomers();


return customers;
}


Note the use of ICollection instead of Collection<>.



Now in my GUI, I need to cast the results back to Collection, like:



Collection customers = (Collection)BL.FindCustomers();



This is because I need to use some Collection<> specific methods on my returned list, which I cannot do with ICollection<>.



Is this the correct usage? Or should I simply change the return type from Collection<> instead to ICollection<> in order to avoid this casting?



Secondly, I did not use IEnumerable because it is more generic than ICollection and does not even have simple properties like Count. And I really don’t see a point in generalizing the return types here. Am I missing something important?


Answer



The whole point of using ICollection is to be more generic and hide more information, which is a good thing.




But if you need to convert it back it has become pointless and you might as well return the more functional Collection< > instead.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...