Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take an optional parameter for Action<T1,T2> [duplicate]

I have a class that currently looks like this:

public Action<string> Callback { get; set; }

public void function(string, Action<string> callback =null)
{
   if (callback != null) this.Callback = callback;
   //do something
}

Now what I want is to take an optional parameter like:

public Action<optional, string> Callback { get; set; }

I tried:

public Action<int optional = 0, string> Callback { get; set; }

it does not work.

Is there any way to allow Action<...> take one optional parameter?

like image 779
user2846737 Avatar asked Dec 29 '25 16:12

user2846737


1 Answers

You can't do this with a System.Action<T1, T2>, but you could define your own delegate type like this:

delegate void CustomAction(string str, int optional = 0);

And then use it like this:

CustomAction action = (x, y) => Console.WriteLine(x, y);
action("optional = {0}");    // optional = 0
action("optional = {0}", 1); // optional = 1

Notice a few things about this, though.

  1. Just like in normal methods, a required parameter cannot come after an optional parameter, so I had to reverse the order of the parameters here.
  2. The default value is specified when you define the delegate, not where you declare an instance of the variable.
  3. You could make this delegate generic, but most likely, you'd only be able to use default(T2) for the default value, like this:

    delegate void CustomAction<T1, T2>(T1 str, T2 optional = default(T2));
    CustomAction<string, int> action = (x, y) => Console.WriteLine(x, y);
    
like image 107
p.s.w.g Avatar answered Dec 31 '25 06:12

p.s.w.g