This is a simplified version of the problem that I've been trying to solve recently. I have the following two classes:
class Container { }
class Container<T> : Container
{
T Value
{
get;
private set;
}
public Container(T value)
{
Value = value;
}
public T GetValue()
{
return Value;
}
}
Now I want to do:
Container<int> c1 = new Container<int>(10);
Container<double> c2 = new Container<double>(5.5);
List<Container> list = new List<Container>();
list.Add(c1);
list.Add(c2);
foreach (Container item in list)
{
Console.WriteLine(item.Value);
Console.WriteLine(item.GetValue());
}
What is the best way to implement this functionality? Is it possible at all? I think I might have on solution to this issue, but I consider it a work-around and I am looking for some design pattern.
Thank you in advance for your responses, Michal.
P.S.
I tried with interfaces, virtual functions, abstract classes, abstract functions; even creating functions in a superclass that would call the properties of the real type by name (using reflection)...I am still not able to achieve what I want...
You could the base class Container into an interface:
Which is then explicitly implemented in the derived classes:
Change the list to contain IContainer elements:
The public Value property on Container is kind of confusing, but you get my point.