Search code examples
c#inheritanceinterfacefluent

Scaleable Fluent Interface with Inheritance


I am trying to write a Fluent Interface API that can scale well. What structure would allow for strong types, inheritance, and state-full(as in the class type)?

For instance

 class A
 {
     public A PerformFoo()
     {
         //do stuff
         return this;
     }
 }
 class B : A
 {

 }

I would like class B when calling PerformFoo to return B not A, ideally I would prefer to stay away from

public class B : A
{
    public new B PerformFoo()
    {
        return (B)base.PerformFoo();
    }
}

As to not have to override or new Every method in child classes. I believe I would need to use generics that use Type signatures.

I don't want to use extension methods but can't seem to get the structure right when doing it with casting (T) like in the answer for [a link]Fluent interfaces and inheritance in C#


Solution

  • finally i figured out the structure

    public class A {}
    public class B : A {}
    public class C<T> : A where T : C<T>
    {/*most methods return T*/}
    public class D:C<D>
    {/*all methods return this*/}
    public class E<T>:C<T> where T:E<T>
    {/*all methods return T*/}
    public class F:E<F>{}
    

    now even specialized generics will still return the original caller