Why should I replace CollectionBase with Generics?

I'm not looking like, I was looking for why? I could not find a direct answer to this question.

+4
source share
6 answers

Yes. CollectionBase was a previous attempt and a way to ensure type safety.

General characteristics give you these benefits, but add two more HUGE benefits:

  • With generics, you no longer have boxing and unboxing every time you access your collection. It provides a great spirit. advantage.
  • With generics, you can use a single implementation for all your types. In CollectionBase, each type requires a special implementation, which leads to a huge amount of duplicated code (i.e., to the possibility of errors).

Edit:

I thought of several other good reasons to move your code to use shared collections:

  • Using shared collections will allow you to directly use LINQ for objects in your collections without requiring calls to Cast<T> (CollectionBase does not implement IEnumerable<T> , only IEnumerable ).
  • Ensure compatibility with any new code that must always be executed using the new shared collections.
+12
source

Strongly typed access to all different types of collections with just the input <type> ?

EDIT: If you delete existing and working code, the only reason could be performance, as indicated elsewhere.

+4
source

Enter security without having to write a lot of code for each type. If you look at an example in the MSDN CollectionBase documentation , you need to write a lot of code labels to make a set of Int16 types. With generics, it is slightly shorter:

 var myListofInt16 = new List<Int16>(); 

Every bit of code that you donโ€™t need to write is a code that you wonโ€™t be mistaken (I say that, since it applies to me, I am sure that this applies to others as well! ;-)

+2
source

With CollectionBase, you need to expand to provide the functionality that generic tools do initially. You must write in all the plumbing to take into account the type safety in the subclasses that you create from it. Generics are not necessary. Do you need to convert to generics? It depends on your situation, but I will not use it in the future.

In addition, using generics instead of the collection database gives you all the extension methods written in .net to simplify common tasks. MS insists on the use of generics and is actively developing their adoption. They are likely to continue to develop their functionality.

+1
source

You want to use Generics to avoid boxing.

This is a good article that lists the benefits of generics.

0
source

There is another reason.

LINQ

You can only use LINQ methods in a collection that implements IEnumerable<T> .
To use LINQ for CollectionBase , you must either first call Cast<T> or manually implement IEnumerable<T> in the class.
Inheriting from ObjectModel.Collection<T> , you get an implementation of IEnumerable<T> for free.

0
source

Source: https://habr.com/ru/post/1303292/


All Articles