0

I have a method

Append(string text, string color, SomeOtherParamsWeLlPretendDoNotExist){}

I'd like for Append to return a reference to itself, to be able to call it like:

Append("Title","red")(" - more txt", "black")("end","green");

I'm new to C# and this exercise is more of an excuse to grasp how delegates work and what they can do.

As Delegates are strongly typed the first problem i faced was the recursive definition:

//it needs to be something like
public Func<string, string, Func<string, string, Func...>>> Append(..){..}

//i cannot use the code below to define a recursive type because Func is sealed
   //on the line of the pattern found [here](https://stackoverflow.com/questions/647533/recursive-generic-types)
class MyDel: Func<string, string, MyDel>{ }

I tried keeping it simpler by defining the method as

public Func<int, Delegate> Append(string text, string color){
    Console.WriteLine("{0}:{1},text,color);
    return Append;
}

And i wasn't expecting it to work, but it did to some extent:

Append("first","red"); //console output: 'first:red'
Append("first","red")(" second","blue"); //console output: 'first:red second:blue'
Append("first","red")(" second","blue")("third","gray"); //compiler error: "Method name expected at (third call's first parenthesis)"

What is going on in that last case? Can i implement this behaviour at all, and how can i accomplish it?

  • 1
    I wonder if this [question about recursive aliases](https://stackoverflow.com/questions/10466499/is-it-possible-to-declare-a-recursive-using-alias-directive-in-c) has anything to do with this (as in something like `using AppendFunc = System.Func;` to help the compiler). It can sort of work if you use dynamic invocation, rather than rely on static compilation: `Program.Append("first","red")("second","blue").DynamicInvoke(new string[]{"third","gray"});` But not sure why it only works once statically, which is the question. – Nir Maoz Jun 28 '23 at 14:12
  • For most practical purposes, returning an object that may support 1 or multiple methods tends to be far more useful and is the usual basis for a fluent interface. A method that returns a delegate that can only be used to invoke the same method again is far less flexible. – Damien_The_Unbeliever Jun 30 '23 at 05:48
  • You can't achieve this with `Func<>` but you can declare your own recursive delegate. `delegate Blah Blah(string text,string color); ...Blah Append(...){... return this.Append;}` While this is an interesting puzzle, I wouldn't include it in production code. – Jeremy Lakeman Jun 30 '23 at 06:04

0 Answers0