Code example first:
public class Child1 : Parent
{
private int _value;
public int Value => _value;
public void Initialize(Random random)
{
base.Initialize();
_value = random.Next(1,100);
}
}
public class Child2 : Parent
{
private double _value;
public double Value => _value;
public void Initialize(Random random)
{
base.Initialize();
_value = random.NextDouble();
}
}
public class Parent
{
private bool _initialized;
private string _id;
public string Id => _id;
protected void Initialize()
{
if(!_initialized)
{
_id = System.Guid.NewGuid().ToString();
}
}
}
What I want to do:
class Program
{
private Parent[] _things = new Parent[] {new Child1(), new Child2(), new Child1()}
private Random _random = new Random();
static void Main(string[] args)
{
foreach (var thing in _things)
{
thing.Initialize(_random);
}
}
}
But this code doesn't work, because it tries to call the protected initialize instead of the child class initialize. As I have read in this question you can not cast an object to its child class from the parent class.
I feel like logically, this type of construct makes sense, because the parent class can hold all the common fields and logic, while the children have the differences, and do different things in their own initialization methods. I want to handle the mixed bunch of child classes easily in an array and call their initialize function. And there should never exist a parent class that is initialized on its own.
Am I doing something fundamentally wrong and is there a different approach to this kind of construct, that would let me call the initialize method of a bunch of different child classes?
I would really appreciate a working code example.