how to hide base class method and create a-like...

  • Thread starter Thread starter David
  • Start date Start date
D

David

hello...

a want to create my own collection class...
i tryed it two ways, one then declarinf it as of IList interface (not easy
way) and like an ArrayList derived class (easy way)

in both ways i wanted to be able to "Add" o "insert" only objects of sertain
type... let's say derived from "MyClass"
and in both ways i did it by checking it in specific function, example:
public int Add (object value)
{
if (value is MyClass)
// it's good
else
throw...
}

the matter of thing is what i want to have function like
public int Add (MyClass value) ...
and not to see and be able to use
public int Add (object value)...
in windows forms is some how done with
TreeNodeCollection -- how?
 
Basically, you can't use inheritance.

It's a fundamental rule of inheritance (known as the Liskov Substitution
Principle) that anything that you can do to the base class, you can also do
to the derived class. Thus if you can call Add (object) on the ArrayList
base class, you must be able to do it on the derived class.

You want to use containment. Make the ArrayList object a private member of
your collection, rather than its base class. You now write your Add
(MyClass), which does not now override any base class or interface method,
looking something like this:

class MyCollection
{
private ArrayList myList = new ArrayList ();

public int Add (MyClass obj)
{
myList.Add (obj);
}
}

Alternatively, wait until VisualStudio 2005 comes out, and then we'll have
Generics, where you can simply use:

ArrayList <MyClass>

to do what you want.
 
David said:
hello...

a want to create my own collection class...
i tryed it two ways, one then declarinf it as of IList interface (not easy
way) and like an ArrayList derived class (easy way)

in both ways i wanted to be able to "Add" o "insert" only objects of sertain
type... let's say derived from "MyClass"
and in both ways i did it by checking it in specific function, example:
public int Add (object value)
{
if (value is MyClass)
// it's good
else
throw...
}

the matter of thing is what i want to have function like
public int Add (MyClass value) ...
and not to see and be able to use
public int Add (object value)...
in windows forms is some how done with
TreeNodeCollection -- how?

What you are after can be accomplished by inheriting from the CollectionBase
class. It provides an internal ArrayList object to store your information,
and allows you to define the Add, Insert, etc. methods to limit what type of
information is added to your collection.
 
Back
Top