Re: Polymorphism & Collections



For those interested, I am posting below what ended up being the ultimate
solution I came to. This accomplishes both of my goals:

1) Type safety
2) Independence of data layer on extended classes

Your feedback is welcomed and appreciated.

Thanks.
Jerad

//Polymorphic Collections Example

public class MyBaseClass
{
//base member implementation
}

public class MyBaseCollection : ICollection
{
protected ArrayList _innerList;

public MyBaseClass this[int index]
{
get { return (MyBaseClass)_innerList[index]; }
}

public virtual MyBaseClass AddNewItem()
{
MyBaseClass newBaseItem = new MyBaseClass();
_innerList.Add(newBaseItem);
return newBaseItem;
}

//standard collection member implementation
}

public class MyExtendedClass : MyBaseClass
{
public string MyExtendedProperty
{
//get/set implementation
}
}

public class MyExtendedCollection : MyBaseCollection
{
public new MyExtendedClass this[int index]
{
get { return (MyExtendedClass)base._innerList[index]; }
}

public override MyBaseClass AddNewItem()
{
MyExtendedClass newExtendedItem = new MyExtendedClass();
_innerList.Add(newExtendedItem);
return newExtendedItem;
}
}

public class MyDataLayer
{
public void GetRecords(MyBaseCollection myBaseCol)
{
//database implementation

while(dr.Read())
{
//This is critical -- using the collection's AddNewItem
//to instantiate the object will ensure the proper type
//is being instantiated. If the collection is an
//instance of MyExtendedCollection, it will create and
//add an instance of MyExtendedClass to the collection.
//Otherwise, it will add an instance of MyBaseClass.

MyBaseClass myBase = myBaseCol.AddNewItem();

//set myBase's base properties
}
}
}

public class TestClient
{
public void Main()
{
MyDateLayer myDL = new MyDataLayer();

//This will pass an instance of a base collection to the data layer
MyBaseCollection myBaseCol = new MyBaseCollection();
myDL.GetRecords(myBaseCol);
myBaseCol[0].MyExtededProperty = "Not legal";

//This will pass an instance of an extended collection to the data
layer
MyExtendedCollection myExtCol = new MyExtendedCollection();
myDL.GetRecords(myExtCol);
myExtCol[0].MyExtededProperty = "Legal";
}
}


.


Loading