using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
public class ClassA
{
private int _type;
public int Type
{
get { return _type; }
set
{
_type = value;
switch (_type)
{
case 1: MyCol = new List<TypeA>(); break;
case 2: MyCol = new List<TypeB>(); break;
case 3: MyCol = new List<TypeC>(); break;
default: MyCol = null; break;
}
}
}
public IList MyCol { get; set; }
public IList<TypeA> MyColA { get { return (MyCol as List<TypeA>); } }
public IList<TypeB> MyColB { get { return (MyCol as List<TypeB>); } }
public IList<TypeC> MyColC { get { return (MyCol as List<TypeC>); } }
//other properties and methods
}
public class TypeA
{
//class definition
}
public class TypeB
{
//class definition
}
public class TypeC
{
//class definition
}
// Test class
public class Program
{
public static void Main()
{
var a = new ClassA();
a.Type = 1;// a.MyCol is now of List<TypeA>
a.MyCol.Add(new TypeA());
a.MyCol.Add(new TypeA());
a.MyCol.Add(new TypeA());
a.MyCol.Add(new TypeA());
foreach (var n in a.MyCol)
{
Console.WriteLine(n);
}
Console.WriteLine(a.MyColA);
Console.WriteLine(a.MyColB); // return null, since a.MyCol is a List<TypeA>
Console.WriteLine(a.MyColC); // return null, since a.MyCol is a List<TypeA>
try
{
a.MyCol.Add(new TypeB()); // this will throw an exception
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
a.Type = 2; // a.MyCol is now of List<TypeB>
a.MyCol.Add(new TypeB()); // this will not throw an exception
a.MyCol.Add(new TypeB());
a.MyCol.Add(new TypeB());
a.MyCol.Add(new TypeB());
foreach (var n in a.MyCol)
{
Console.WriteLine(n);
}
Console.WriteLine(a.MyColA); // return null, since a.MyCol is a List<TypeB>
Console.WriteLine(a.MyColB);
Console.WriteLine(a.MyColC); // return null, since a.MyCol is a List<TypeB>
}
}
}
If the object have similarities, you'd probably be better off defining this in an interface and implementing it in your child objects (as wdosanjos mentions above).