0

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.

Kasun
  • 642
  • 1
  • 7
  • 16
  • Just use `Parent` with `class Parent : Parent` as wildcard replacement. See also: https://stackoverflow.com/questions/15574977/wildcard-equivalent-in-c-sharp-generics. – Tetsuya Yamamoto Dec 27 '18 at 04:56
  • Thanks, I checked those out. But with that there is not way of using generic methods defined in the Parent class. I'm just looking for a solution that allows the use of those methods – Kasun Dec 27 '18 at 05:00
  • So far (even after the edit) it is still duplicate of https://stackoverflow.com/questions/15574977/wildcard-equivalent-in-c-sharp-generics as what you are asking is not possible in C#. You have to adjust what you are trying to do to match supported behaviors in C# or drop type safety completely and just use `dynamic` all the time. – Alexei Levenkov Dec 27 '18 at 05:28
  • It also may be good idea to read https://stackoverflow.com/questions/1777800/in-c-is-it-possible-to-cast-a-listchild-to-listparent which explains that in C# `G` and `G` have no relationships (which is what you are trying to do). – Alexei Levenkov Dec 27 '18 at 05:32
  • Thanks for the feedback, I'll check for alternatives – Kasun Dec 27 '18 at 05:58

0 Answers0