Hi I want to create my custom collection, I am deriving my custom collection class from CollectionBase class as below:
public class MyCollection : System.Collections.CollectionBase
{
MyCollection(){}
public void Add(MyClass item)
{
this.List.Add(item);
}
}
class MyClass
{
public string name;
}
Let me ask a few questions:
Deriving from List<T>
is somewhat pointless, especially now that it has the IEnumerable<T>
constructor and the availability of extension methods. It has no virtual methods that you can override except Equals
, GetHashCode
, and ToString
. (I suppose you could derive from List<T>
if your goal was to implement Java's toString() functionality for lists.)
If you want to create your own strongly-typed collection class and possibly customize the collection behavior when items are add/removed, you want to derive from the new (to .NET 2.0) type System.Collections.ObjectModel.Collection<T>
, which has protected virtual methods including InsertItem
and RemoveItem
that you can override to perform actions at those times. Be sure to read the documentation - this is a very easy class to derive from but you have to realize the difference between the public/non-virtual and protected/virtual methods. :)
public class MyCollection : Collection<int>
{
public MyCollection()
{
}
public MyCollection(IList<int> list)
: base(list)
{
}
protected override void ClearItems()
{
// TODO: validate here if necessary
bool canClearItems = ...;
if (!canClearItems)
throw new InvalidOperationException("The collection cannot be cleared while _____.");
base.ClearItems();
}
protected override void RemoveItem(int index)
{
// TODO: validate here if necessary
bool canRemoveItem = ...;
if (!canRemoveItem)
throw new InvalidOperationException("The item cannot be removed while _____.");
base.RemoveItem(index);
}
}
I think you would be better off using one of the container classes defined in System.Collections.Generic
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With