Strongly typed arraylist and inheritance issue

D

Dot net work

I thought I'd be clever and create my own strongly typed array list,
because I wanted to be sure that when an object was added to the
arraylist, it would *only* be an object of a class that I had made.

But after I got it all working, I realised that the inheritance
mechanism also allows access to the inherited Add methods, and these
allow you to add objects of any type!

I don't seem to have achieved what I tried to do.

(Please note, if this makes any difference, I am inheriting from a 3rd
party arraylist, and this in turn inherits from the MS arraylist.)

Can any one offer any tips to rectify this problem please?

TIA,
-dnw.
 
M

Mattias Sjögren

Can any one offer any tips to rectify this problem please?

Don't inherit from the array list, just keep it as a private object
and delegate all operations to it.

Of course, this means you can't use the class on places where a
regular ArrayList is expected.



Mattias
 
B

Bob Grommes

Visua Studio 2005 / CLR 2.0 supports generics. The List<T> class would
replace ArrayList and works like so to create strongly-typed list of ints:

List<int> iList = new List<int>();
iList.Add(1);
int i = iList[0]; // look Ma, no casting!

I would not go to great lengths to work up my own solution in CLR 1.1 if I
expect to release under 2.0. Just get the C# Express 2005 beta, familiarize
yourself with what's coming, and write your code with easy retrofit in mind.
Perhaps even consider developing with the beta.

Failing that ... like someone else said you can write your own
strongly-typed alternative, it just will not inherit from ArrayList but
rather will encapsulate it. For guidance, look at some of the collections
in System.Collections.Specialized, where you have for instance a StringList.
Get ahold of the Rotor source code and you can see exactly how they are
implemented.

--Bob
 
D

Dot net work

Very interestingly, what I wanted to achieve is only available in
VB.NET, and not in C#.

Inside VB.NET, if you have a class that inherits another class, and
you use the "shadows" keyword inside your new inherited class, it
completely hides all methods inside the base class whose method name
is the same, but the signatures of the base class methods may vary.

This is exactly what I wanted to achieve - to make the calling code
object.method() syntax not see (and not be able to call) any of the
other methods inside the base class whose method name was the same as
the method name inside the inherited class.

The "new" keyword in C# does not hide the base methods. "shadows" in
VB.NET does.

-dnw.
 
S

Sijin Joseph

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