Search code examples
c#parametersdelegatesrefactoringmethod-call

How to set the values of a delegate's parameters to use for subsequent calls without supplying them each time?


In C#, is there a way to create a delegate with a value, e.g. "MyDelegate("Hello World")", which can be stored in a variable, and then later be invoked with the value it has been given?

For example: (I know this is not how delegates work, it's just pseudocode to make it clearer what I'm looking for)

delegate void MyDelegate(string text);

void WriteText(string text) 
{
    Console.WriteLine(text)
}

MyDelegate newDelegate = WriteText("Hello World") //Store the function and a string value 

newDelegate.InvokeWithOwnValue() //Invoke the delegate with the string value that we've given it before

//Output: "Hello World"

I don't know if this is even possible with Delegates, or if there is actually something else I'm looking for.


Solution

  • You can capture the value by using a lambda, but you would need a different delegate type, as now you would be invoking with no parameters.

    It's a lot easier to just use the various Action and Func delegate types.

    void WriteText(string text) 
    {
        Console.WriteLine(text);
    }
    
    Action newDelegate = () => WriteText("Hello World"); //Store a string value 
    
    newDelegate(); //Invoke the delegate with the string value that we've given it before
    
    //Output: "Hello World"
    
    Action<string> originalDelegate = WriteText;  // if you already have a delegate
    
    Action newDelegate = () => originalDelegate("Hello World"); //Store the delegate and a string value 
    
    newDelegate(); //Invoke the delegate with the string value that we've given it before
    
    //Output: "Hello World"