3

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"

Stargateur
  • 24,473
  • 8
  • 65
  • 91
jarjar27
  • 117
  • 1
  • 14

2 Answers2

3

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.

BassaForte
  • 86
  • 1
  • 4
  • Since default(Action) is null, there is no benefit. Either one works - I just forgot that Action can be set to null as an optional parameter. – BassaForte Dec 14 '17 at 00:15
1

Suppliment to Chiris's answer, you could achieve goal by setting anotherFunction in the code. e.g.:

void function(Action func = null) {
    if(func == null)
        func = anotherFunction;
}
Evan Huang
  • 1,245
  • 9
  • 16