I am trying to achieve something specific in c# and I don't know if it has a name (or even if it's good practice). I tried to simplify the code as much as possible because this is a generic problem (no pun intended, what I mean by that is that it doesn't depend on the rest of the implementation) Basically I have a generic class Class1, a class A, a class B that inherits from A, and another class Class2 that inherits from Class1 with B as the generic parameter. The issue is that I get an error "cannot convert from 'Class2' to 'Class1'" when I try to cast.
I tried different combinations and have spent hours and checked dozens of links but so far I can't seem to find an answer to this exact problem. Keep in mind I am fairly new to programming (a few years but I learned by myself)
public class Class1<T> where T : A
{
public string name;
}
public class Class2 : Class1<B> { }
public class A { }
public class B : A { }
//if I change the parameter type to Class1<B>, but that defeats the purpose
//of being able to call this function with any class that extends Class1
void TestFunction(Class1<A> test)
{
Debug.Log(test.name);
}
//I basically want to do this
var instance = new Class2();
//I can't do this because instance is of type Class2 but can't be converted
//to Class1<A>
TestFunction(instance);
I want to be able to have classes that extend class1, like class2, with parameters that extend A, like B, but for a reason that I can't quite grasp it doesn't work this way. Thanks for any help! I'm kinda in over my head and feel like I will never find a solution that works at my level.