Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CollectionBase vs generics

Tags:

c#

.net

generics

I am migrating an application from .NET 1.1 to .NET 2.0. Should I remove all uses of CollectionBase? If so, what is the best strategy for migration?

like image 581
leora Avatar asked Nov 22 '08 10:11

leora


People also ask

What is generic and nongeneric?

A Generic collection is a class that provides type safety without having to derive from a base collection type and implement type-specific members. A Non-generic collection is a specialized class for data storage and retrieval that provides support for stacks, queues, lists and hashtables.

What is the difference between generics and collections in C#?

Generics are similar to collections, but implemented using Type parameters. Generic collections accept a type parameter and accept the elements of only those type for which the generic collection is instantiated. These enforce strict type checks.

What is CollectionBase C#?

Collections namespace contains CollectionBase class. It is an abstract class that implements only necessary methods of IEnumerable and ICollections interface.

What does generic collection mean?

A generic collection is strongly typed (you can store one type of objects into it) so that we can eliminate runtime type mismatches, it improves the performance by avoiding boxing and unboxing.


2 Answers

Yes, the best classes to look at are in System.Collections.Generic.
I usually use List.

There are two approaches you can use either:

A

public class MyClass
{
  public List<MyItem> Items;
}

B

public class MyItemCollection : List<MyItem>
{
}

public class MyClass
{
  public MyItemCollection Items;
}

The two approaches only differ very slightly and you only need to use method (B) if you plan on extending the functionality of List.

Here's a link with more info:
http://msdn.microsoft.com/en-us/library/6sh2ey19(VS.80).aspx

With regards to the classes that you've already implemented, you can remove all of the functions which are specified in the IList interface. e.g.

public int Add(InstrumentTradeDataRow instTrade) { return List.Add(instTrade); }

This can be removed because List already implements a type safe Add function for you.

See this link for more information:
http://msdn.microsoft.com/en-us/library/3wcytfd1(VS.80).aspx

like image 126
Mark Ingram Avatar answered Oct 14 '22 13:10

Mark Ingram


Generally, List<T> does most of what you normally want. If you want to customize behaviour, you should inherit from Collection<T> - this has virtual methods so you can tweak behaviour when adding/removing/updating etc. You can't do this with List<T> since there are no (uesful) virtual methods.

like image 35
Marc Gravell Avatar answered Oct 14 '22 15:10

Marc Gravell