Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Subscribe a Method to a System.Action, but with predefined arguments

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading