IList implementation

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
 
J

Jay B. Harlow [MVP - Outlook]

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
 
M

Michael Lang

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top