The title says it all. I am writing a function that takes in another function as an argument like so:
void function(Action func) { }
which works just fine. I want to be able to call the function without any parameters, though, so I can use that function as an argument to another function and so on. I know default values for parameters can be set by:
void function(int x = 0) { }
but if I try:
void function(Action func = anotherFunction) { }
I get an error that states "Default parameter value for 'func' must be compile-time constant". Is it possible to set a default function? if so, how? This is being used in a cross-platform Xamarin Forms mobile application, so cross-platform functionality is necessary. All functions return void and only take in the one argument. The argument function determines which function gets called after the user clicks "Submit"
Something you could do is
void function(Action func = default(Action)) { }
The func parameter would be optional, but it would have a default value of null. I'm pretty sure you can't allow func to be set to a default action that already exist, because it is a reference type and cannot be constant.
Here's some more info on the default keyword
EDIT: I suppose if you wanted the method to do something if 'func' isn't set, you would check if it's null (which you should always do before invoking a callback) and if it is, do something else (you could specify what action or callback to do there).
EDIT2: As mjwills mentioned, you could also do void function(Action func = null) { }
The default keyword would be more useful when the parameter you want to make optional is a struct.
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