-1

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#

Community
  • 1
  • 1
Michael Rieger
  • 472
  • 9
  • 18
  • 2
    You haven't actually asked a question... you've just given some code, and some code that calls it. What's the issue? – Jon Skeet Jul 16 '14 at 20:59

2 Answers2

0

If I understand correctly, the issue is that Method1 is not behaving the way you'd like, as it downcasts to A, preventing you from calling further methods. One way around this is to shadow the method in subclasses:

public class A
{
    public A Method1()
    {
        return this;
    }
}

public class B : A
{
    public new B Method1()
    {
        return (B)base.Method1();
    }
}
Dan Bryant
  • 27,329
  • 4
  • 56
  • 102
  • unfortunately that doesn't scale well to have every method in the child class to nest override every shared method in the base case – Michael Rieger Jul 17 '14 at 13:11
0

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

Michael Rieger
  • 472
  • 9
  • 18