Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Giving an object a collection as a property 1

Status
Not open for further replies.

crazyboybert

Programmer
Jun 27, 2001
798
GB
Hi all

What is the best way to give an object a publicly accesible collection of 0...* length regardless of the type of object stored in the collection. At the moment I commonly use ArrayLists for this by having a publicly accessible ArrayList and private member ArrayList pair into which I put the objects that make my collection. Is this the best way of doing this or is there a more correct method of giving an object a collection as a property?

Rob

Go placidly amidst the noise and haste, and remember what peace there may be in silence - Erhmann 1927
 
You can do that, but then the caller can put anything in your collection, not just what you'd like them to put in there.

When Whidbey comes out, it will have generics, where you can control the datatype of what gets stored in your collections very easily. But for now, it takes a lot of code. Take a look at the FAQ for strongly-typed collections in this forum.

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
A Hashtable object allows to store heterogenous object types and the searching and retrieving are easier and faster than in most collections.
Example:
class A
{
public A(){};
public A(int a){//..};
}
class B {};
class C:B {};
class D{};

Hashtable = new Hashtable();
ht.Add("nameobj1",new A());
ht.Add("nameobj2",new A(19));
ht.Add("nameobj3",new B());
ht.Add("nameobj4",new C());
ht.Add("nameobj5",new D());

Now, retrive the object from the hashtable :
if (ht.ContainsKey("nameobj2"))
{
object o = ht["nameobj2"];
System.Type tp = o.GetType(); // retrive the type of object
}
Or search by a given object using the ContainsValue() method.
-obislavu-

 
Thanks ChipH thats exactly what I am looking for :).

Thanks also to obislavu for your response. I can see the benefit of HashTables and how they can be used within Chip's strongly typed collections.

Rob

Go placidly amidst the noise and haste, and remember what peace there may be in silence - Erhmann 1927
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top