Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a function as argument AND set a default argument

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"

like image 283
jarjar27 Avatar asked Apr 17 '26 18:04

jarjar27


1 Answers

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.

like image 119
BassaForte Avatar answered Apr 20 '26 08:04

BassaForte