Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can somehow a method from base class return child class?

Tags:

c#

I'll give an example, so 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 as Common() returns Base, and XMethod() is not defined in Base.

Is there any possible way i could acomplish this ?

I'm asking because i have a BaseComponent, and a lot of other Components that inherit this class, and i have to declare the common methods in each one, just to call base.Method() inside.

Thanks for your help.

PS: without using generics and specifying the child's type:

var a = new XBase().Common<XBase>().XMethod();
like image 880
Cristi Pufu Avatar asked Nov 19 '13 17:11

Cristi Pufu


1 Answers

You could make Base generic and use the 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;
     }
}

Then you can just use:

var a = new XBase().Common().XMethod();
like image 96
D Stanley Avatar answered Oct 25 '22 19:10

D Stanley