IList implementation

  • Thread starter Thread starter Rodney
  • Start date Start date
R

Rodney

I want to create a class that implements IList, but who's Add and
indexer only accepts and returns objects of a specific type (not the
generic 'object').

I believe Microsoft have done this somehow in the
StatusBarPanelCollection, which implement IList but only allows you to
add StatusBarPanels. It seems odd to me that this class implements
IList as the CopyTo method required is appears not to be implemented.

Can someone please shed some light on what's going on here and how i
can achieve my objective?


Aaron
 
Rodney,
C# or VB.NET?

In C# you need to use 'Explicit interface member implementations:
http://msdn.microsoft.com/library/d.../en-us/csspec/html/vclrfcsharpspec_13_4_1.asp

Something like:
class ListEntry : ICloneable
{
object ICloneable.Clone() { }
ListEntry Clone() { }
}

Which effectively hides the ICloneable method, allowing you to define a
typesafe Clone method.

For VB.NET, you can do something similar. Change the name that implements
the method, making it private.

Something like:
Class ListEntry
Implements ICloneable

Private Function ICloneable_Clone() As Object _
Implements ICloneable.Clone
End Function

Public Function Clone() As ListEntry
End Function

End Class

Hope this helps
Jay
 
The easy way is to create a custom collection that inherits from
CollectionBase. CollectionBase does implement IList. CollectionBase
supplies you with a private InnerList property of type ArrayList to contain
your items. CollectionBase only exposes Clear(), Count, RemoveAt(),
GetEnumerator(), and base object methods. You MUST implement your own
methods for Add() and for the indexer(s). The return type of the indexer
should be of your custom type. You also must implement your own
constructor, as the CollectionBase constructor is "protected" scope.

For example (typed on the fly, not syntax checked):
==== Code ======================================
public class Employee{...}
public class EmployeeCollection: System.Collections.CollectionBase
{
public EmployeeCollection():base(){}
public Employee this[int index]
{
get
{
return (Employee)this.InnerList[index];
//item in collection cast to custom type
//since you enforce only correct type is added, no
// try/catch block is necassary
// only error could be an ArgumentOutOfRangeException
}
}
public void Add(Employee emp)
{
this.InnerList.Add(emp);
}
// recommend you expose other InnerList properties/methods
// such as CopyTo, Sort, Remove, Insert, etc...
}
==== End Code ==================================

See the help on CollectionBase for more help.

Michael Lang, MCSD
 
Back
Top