The blow code is not running giving the error: "Error CS1503: Argument 1: cannot convert from ‘Child1’ to ‘Test<bool, object>’", I am creating the abstract class, which takes the Same abstract class as a parameter in the constructor. and After creating the child class of them and passing another child class as a parameter to one’s constructor giving compilation error as mentioned.
Tried ChatGPT it says logically code is correct, but why visual studio code is giving compile time error.
https://learn.microsoft.com/en-us/answers/questions/1379331/compilation-error-cs8625-c
abstract class Test<A, B>
{
private Test<B, object> t1;
public Test(Test<B, object> t)
{
t1 = t;
}
}
class Child1 : Test<int, string>
{
public Child1(Test<string, object> t) : base(t)
{
}
}
class Child2 : Test<string, bool>
{
public Child2(Test<bool, object> t) : base(t)
{
}
}
class Main
{
public void Init()
{
Child2 c2 = new Child2(null);
Child1 c1 = new Child1(c2);
}
}
2
Answers
That error looks right to me.
t1
is aChild1
, which is aTest<string, string>
.t2
is aChild2
.Child2
‘s constructor takes aTest<bool, object>
t1
cannot be converted from aTest<string, string>
to aTest<bool, object>
because its specified class-types don’t match. Simply, astring
is not abool
.Maybe, you want the
Child1
andChild2
sub-classes to be generic too.I reproduce the code in my local like below.
Here is the working sample, it can help you fix it.