I have generic class which has been extended by few child classes.
class Parent<T>
{
public T test;
protected Parent(T test)
{
this.test = test;
}
}
class ChildA : Parent<int>
{
public ChildA(int test) : base(test)
{
}
}
class ChildB : Parent<string>
{
public ChildB(string test) : base(test)
{
}
}
The child class that I want to use in code is determined by some program logic. I would like to have a parent container and assign the the determined child object to it so that I can use the methods defined in the parent class.
public static void Main()
{
Random rand = new Random();
Parent<dynamic> child; // parent reference ** line at question
if (rand.Next(100) > 50)
{
child = new ChildA(1);
}
else
{
child = new ChildB("A");
}
Console.WriteLine(child.test);
}
I've used the generic type in reference object as dynamic
as placeholder. Compiler gives errors saying it cannot implicit convert between types.
in Java you can use generic wildcards like
Parent<?> child;
if(Math.random() > 0.5) {
child = new ChildA(1);
}else {
child = new ChildB("A");
}
child.print();
and compiler can determine the child object to run the correct method. How can I achieve the similar flow in C#?
Edit: as suggested in here Wildcard equivalent in C# generics, using another interface allows holding a child objects using a single references, but since that interface doesn't contain the necessary generic methods defined in the parent class, it's not really useful.