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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With