0

I have the following:

var availableDelegates = new Dictionary<string, SampleHandler>{
    {"TestWithNoParams", SampleHandlerOne }, // this is what I have now - working
    {"TestWithParamSetA", SampleHandlerTwo } // need this
    {"TestWithNoParams", SampleHandlerTwo } // and this - working
}

public static SampleHandler SampleHandlerOne(){
     // do stuff - working
}

// v1
public static SampleHandler SampleHandlerTwo(){
     // do stuff without parameters - working
}

// v2
public static SampleHandler SampleHandlerTwo(HandlerTwoParams params = null) { // trying to update to support optional params
     // do stuff with parameters - not working
     // params.Foo = bar
}

How can I pass optional parameters to a delegate? The idea would be that I can do:

if (someCondition)
    availableDelegates[target].Invoke(optionalParams);
else
    availableDelegates[target].Invoke();
SB2055
  • 12,272
  • 32
  • 97
  • 202

1 Answers1

0

You can achieve exactly what you're looking for with optional parameters on your delegate methods, passing the parameters via the Invoke method. This previous answer shows how this can be done: Can a Delegate have an optional parameter?

ZippyZippedUp
  • 458
  • 5
  • 14