0

I have my code posted below and it gives this error- cannot convert from 'BaseClass' to 'DerivedFromBaseClass' But i understand why I get this error. because 'this' is BaseClass . it's not not DerivedFromBaseClass

I can get the type for the class who's derived from BaseClass by using DerivedFromBaseClass -in this case "public class C" However I don't know how to get the instance of the class.

I want to be able to get the instance of DerivedFromBaseClass inside the BaseClass. and then use it as a parameter for the constructor for NestedClass. ie- this gets the instance of the "BaseClass". I want to get the instance of the derived class "C"

public abstract class BaseClass<DerivedFromBaseClass> where DerivedFromBaseClass : BaseClass<DerivedFromBaseClass>
{
    NestedClass nestedClass;
    public BaseClass()
    {
        nestedClass = new NestedClass(this);
    }

    public class NestedClass
    {
        public NestedClass(DerivedFromBaseClass _parameter)
        {
        }
    }
}
public class C : BaseClass<C>
{}

Sorry if this is worded bad I'm kind of new to this.

Sammy
  • 1
  • 1
  • 2
    The fact you want to do this, leads me to suspect you have an XY problem. – Mitch Wheat Mar 22 '21 at 05:04
  • you would have to do something like `NestedClass` but why would you want to do this? – chancea Mar 22 '21 at 05:05
  • 1
    Also complete side note, I think it is easier to read generics if you pre-fix them with something like `T` so `BaseClass where TDerivedFromBaseClass : BaseClass` – chancea Mar 22 '21 at 05:06
  • @chancea Ok thanks i will start using T as a pre-fix. I dont need NestedClass because its nested in "BaseClass" so it already has the type parameter. The main issue is the fact that "this" refers to an instance of BaseClass and not an instance of DerivedFromBaseClass. I need a way to get the instance of the derived class "C" – Sammy Mar 22 '21 at 05:15

0 Answers0