Can a method from a base class somehow return a child class?

I will give an example so that you can better understand what I mean:

public class Base
{
      public Base Common()
      {
          return this;
      }
}

public class XBase : Base
{

     public XBase XMethod()
     {
          return this;
     }
}

I want to be able to do something like:

var a = new XBase().Common().XMethod();

but this is not possible because it Common()returns Base, XMethod()not defined in Base.

Is there any possible way I could do this?

I ask because I have BaseComponentmany others Componentsthat inherit this class, and I have to declare common methods in each of them, just to call base.Method()inside.

Thank you for your help.

PS: without using generics and specifying the type of child:

var a = new XBase().Common<XBase>().XMethod();
+4
source share
2 answers

Base generic Curiously Repeating Template Pattern:

public class Base<T> where T : Base<T>
{
      public T Common()
      {
          return (T)this;
      }
}

public class XBase : Base<XBase>
{
     public XBase XMethod()
     {
          return this;
     }
}

:

var a = new XBase().Common().XMethod();
+6

Base XMethod, , XMethod, , ?

public abstract class Base<T>
{
      public Base Common()
      {
          return this;
      }

     public abstract T XMethod();
}

public class XBase : Base<XBase>
{

     public override XBase XMethod()
     {
          return this;
     }
}
+4

All Articles