1

So I have this function that takes a function with no parameters:

public static bool RetryUntilSuccessOrTimeout(Func<bool> task, TimeSpan timeSpan)
    {
        bool success = false;
        int elapsed = 0;
        while ((!success) && (elapsed < timeSpan.TotalMilliseconds))
        {
            Thread.Sleep(1000);
            elapsed += 1000;
            success = task();
        }
        return success;
    }

And then I have a bunch of functions like:

private static bool OnDeleted(object source, FileSystemEventArgs e){...}
private static bool OnChanged(object source, FileSystemEventArgs e){...}
private static bool OnCreated(object source, FileSystemEventArgs e){...}

I have a function that takes same aruments as those three. So I have that information provided. Is there a way to pass these function as ones not taking any arguments (because I provide them) so i can pass it into the "task" of RetryUntilSuccessOrTimeout() ?

An encapsulating image of the problem:

OnDirEvent

  • Iam innerly cringing when I see any func called like this. In your situation its ok, when the func is null you probably want to raise an exception. I habitly call these by `task?.Invoke() ?? true` when a plausible default is at hand. Otherwise handle null ref in place / upstream. – Patrick Artner Jan 10 '18 at 16:07

1 Answers1

3

Yes. Basically you just do

() => func(a, b)
Adam Brown
  • 1,667
  • 7
  • 9
  • 1
    What you want is called "partial function application". C# doesn't have language-level support for it like some languages (F#, Haskell), but using lambda expressions works in some cases. – JamesFaix Jan 10 '18 at 16:06
  • @stt106 No, it's not. It's partial function application, as was mentioned in the previous comment. Currying that function would be taking a `Func` and creating a `Func>`. – Servy Jan 10 '18 at 16:12