Hello,
I've got a c++ background and i'm wondering what's the best approach to this problem.
I've got a base class Animal with a set of minimal properties for an animal. From animal i've
derived a Dog and a Cat class which are extended with specific properties of it's species. Now i want
a collection to store these animals in. I've created an Collection derived from CollectionBase (see code).
But when i add a Dog or a Cat to this collection i get an exception even when i cast the cat or dog back
to it's base class.
Is there a collection to solve this problem. Which can take the base class
using System;
using System.Collections;
namespace Petshop
{
public class AnimalCollection : CollectionBase
{
public Animal this[ int index ]
{
get { return( (Animal) List[index] );}
set { List[index] = value;}
}
public int Add( Animal value )
{
return( List.Add( value ) );
}
public int IndexOf( Animal value )
{
return( List.IndexOf( value ) );
}
public void Insert( int index, Animal value )
{
List.Insert( index, value );
}
public void Remove( Animal value )
{
List.Remove( value );
}
public bool Contains( Animal value )
{
// If value is not of type Animal, this will return false.
return( List.Contains( value ) );
}
protected override void OnInsert( int index, Object value )
{
if (value.GetType() != Type.GetType("Petshop.Animal"))
{
throw new ArgumentException( "value must be of type Animal.", "value" );
}
}
protected override void OnRemove( int index, Object value )
{
if (value.GetType() != Type.GetType("Petshop.Animal"))
{
throw new ArgumentException( "value must be of type Animal.", "value" );
}
}
protected override void OnSet( int index, Object oldValue, Object newValue )
{
if (newValue.GetType() != Type.GetType("Petshop.Animal"))
{
throw new ArgumentException( "newValue must be of type Animal.", "newValue" );
}
}
protected override void OnValidate( Object value )
{
if (value.GetType() != Type.GetType("Petshop.Animal"))
{
throw new ArgumentException( "value must be of type Animal." );
}
}
}
}
Cheers
Erik
ps. No cats and dogs were harmed during testing of this code.