p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   .NET Framework 2.0 (http://p2p.wrox.com/forumdisplay.php?f=141)
-   -   Object Design Pattern problem (http://p2p.wrox.com/showthread.php?t=47438)

aldwinenriquez September 6th, 2006 12:26 AM

Object Design Pattern problem
We have an object called Product and ProductCollection defined below:
class Product{
public string Name;
public Type.Category Category;

class ProductCollection{
public Product[] List;

what we want to do is to add an attribute to the Product class by creating a derived class called ProductChild(inherits from Product) which will contain the additional attributes.

class ProductChild : Product{
public string AdditionalAttribute;

class ProductChildCollection{
public new ProductChild[] List;

The problem is how to to Create a ProductChildCollection class and cast(convert) the parent ProductCollection into ProductChildCollection without iterating throught the Product List in the ProductCollection.

ProductChildCollection childCollection = (ProductChildCollection)ProductCollection();//casting problem, cannot cast a parent into a child

Our initial solution is to iterate through the ProductCollection and generate child objects from that.

Once that is done we can then set the properties of the additional attributes into each of the ProductChild List items from ProductChildCollection class.

Any ideas?

"Dont you ever give up!"

Ankur_Verma September 6th, 2006 03:08 AM

Surely, with what you have, casting wont work the way you
have proposed here. But what you can do is to write all the
conversion/traversal logic in a member function or an operator
overload in one of these collection classes or in a common function
which does the conversion whenever its needed.

I would add though, that there are better ways of implementing
collections. You could have based these collection classes on
collection and enumeration interfaces, which makes traversal
easy. It would have also helped you in keeping the things cleaner
and casting issues would be much easier to manage as the collection
would all have a common base.


aldwinenriquez September 7th, 2006 04:10 AM

Thanks Ankur, I'll be trying explicit casting/conversions first,then if it didn't worked Il go with your idea. Thanks anyway.

"Dont you ever give up!"

All times are GMT -4. The time now is 01:50 PM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.