Home > Back-end >  C# Subscribe a Method to a System.Action, but with predefined arguments
C# Subscribe a Method to a System.Action, but with predefined arguments

Time:12-26

I have a class that is listening to a lot of action's, and then when these are invoked do a similar thing but to different objects depending on which action was invoked. My thoughts are:

If I have

System.Action<SomeType> SomeAction;
void SomeMethod(SomeType type);

I can do

SomeAction  = SomeMethod;

My question is then, if I have another class say

void SomeOtherMethod(SomeType type, SomePredefinedType)

Is there a way to do something like

SomePredefinedType SomeValue;
SomeAction  = SomeMethod(SomeValue);

that is, to Subscribe a method with two arguments to a action with one argument by predefining the exces argument?

CodePudding user response:

You can't do it with a method group conversion like this, but you can easily do it with a lambda expression:

SomePredefinedType extraArgument = ...;
SomeAction  = value => SomeOtherMethod(value, extraArgument);
  •  Tags:  
  • c#
  • Related