OO Design Question - Strongly typed ArrayList

  • Thread starter Thread starter Bill Cohagan
  • Start date Start date
B

Bill Cohagan

I'm trying to figure out the "best" way to implement a strongly typed
ArrayList. Using inheritance is one approach. It has the advantage that I
only have to write overrides for the Add method and indexer. There are
problems with this however. First the indexer "override" has a different
return type. This doesn't cause a compile time error, but using the indexer
doesn't seem to produce a properly typed expression. The Add override must
have an arg of type object so the method doesn't reflect the strong
typing -- until run time when the my hand coded type check is run. I've
added an Add overload that uses a strongly typed arg, but the original
method still appears in the command completion popup.

An alternative approach would be to use composition, but this requires that
I implement wrapper methods for all of the ArrayList methods that I want to
make available in the strongly typed ArrayList class.

I think the latter (composition) approach provides the best solution in
terms of providing a truly strongly typed object, but am bothered by the
need for the "duplicate" methods.

Is there another alternatives, suggestions?

Thanks in advance,
Bill
 
Hello,

If you want a strongly-typed collection, the easiest thing to do is inherit
from CollectionBase and verify your values in the OnVerify method - but you
knew that already. ;-) However, if you want type-safe member signatures,
you'll need to use composition. Try this:

class MyCollection : IList {
...
public int Add(MyType value) {
...
}
...
int IList:Add(object value) {
if (value is MyType) {
return Add(value as MyType);
} else {
throw new ArgumentException();
}
}
}

Using this notation, Add(object) is only there to satisfy the interface
implementation; it will only be visible if the collection is cast to IList.
Attempting to add an instance of any type other than MyType to the
collection will cause a compile-time error (unless the type of said instance
can be implicitly converted to MyType), as long as you're working with a
MyCollection reference. If the collection is cast to IList at some point,
adding an object of an inappropriate type will throw an ArgumentException at
runtime.
 
Ugh, my mistake - the second method's seiganture should read:

int IList.Add(object value)

Note the period in place of the colin.
 
Omni
Thanks for the suggestion. This is pretty much what I've already tried
(via inheritance). I guess that using an interface keeps the IList.Add
method from showing up in the pop up though, right? The OnVerify approach
doesn't solve the compile-time problem.

Thanks again,
Bill
 
Back
Top