Need explanation on creating a custom collection.

  • Thread starter Thread starter Ken Varn
  • Start date Start date
K

Ken Varn

I want to create a custom collection class that is similar to something like
the System.Windows.Forms.Control.ControlCollection.

I notice that this collection implements IList, ICollection, IEnumrable, and
ICloneable. I have tried to create a similar class, but one thing that I
cannot seem to understand is that the ControlCollection provides overrides
to the interfaces with specific object types rather than the generic object
class. i.e., Add method accepts a Control type and not a generic Object
type as is specified in IList.

When I have tried to do the same, I cannot get the compiler to allow me to
specify a method with a more specific type as an override for the interface.
Can someone explain how to do this?

C# snippet example:

public class MyClass : IList
{
public virtual void Add(Control.Label MyLabel); // How can I implement
IList.Add with a specific type?

}





--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.
(e-mail address removed)
-----------------------------------
 
Hi Ken,

You can do so inheriting from CollectionBase. CollectionBase is intended to
be used for this, it use an ArrayList internally to keep the items and you
provide the methods (Add,Delete, etc ) with the signature that you need.

Here is an example from one of my projects:
As you can see the class use the InnerList to keep the items, and as the
only way to access it is using your class's interface you can assure that
all the elements are of your selected type.
public class LocationPointCollection:CollectionBase

{

public LocationPoint Insert( int index, LocationPoint newelem )

{

this.InnerList.Insert( index, newelem);

return newelem;

}

public LocationPoint Add( LocationPoint newelem)

{

this.InnerList.Add( newelem);

return newelem;

}


Hope this help,
 
Thanks! That clears things up a bit. I'll give that a try.

--
-----------------------------------
Ken Varn
Senior Software Engineer
Diebold Inc.
(e-mail address removed)
-----------------------------------
Ignacio Machin said:
Hi Ken,

You can do so inheriting from CollectionBase. CollectionBase is intended to
be used for this, it use an ArrayList internally to keep the items and you
provide the methods (Add,Delete, etc ) with the signature that you need.

Here is an example from one of my projects:
As you can see the class use the InnerList to keep the items, and as the
only way to access it is using your class's interface you can assure that
all the elements are of your selected type.
public class LocationPointCollection:CollectionBase

{

public LocationPoint Insert( int index, LocationPoint newelem )

{

this.InnerList.Insert( index, newelem);

return newelem;

}

public LocationPoint Add( LocationPoint newelem)

{

this.InnerList.Add( newelem);

return newelem;

}


Hope this help,
 
Back
Top