Is it possible to declare a method as a parameter in C #?

For example, the main method I want to name is the following:

public static void MasterMethod(string Input){ /*Do some big operation*/ } 

Normally I would do something like this:

 public static void StringSelection(int a) { if(a == 1) { return "if"; } else { return "else"; } } MasterMethod(StringSelection(2)); 

But I want to do something like this:

 MasterMethod( a = 2 { if(a == 1) { return "if"; } else { return "else"; } }); 

Where 2 is somehow passed into the operation as an input.

Is it possible? Does it have a name?

EDIT :: Note: MasterMethod is an API call. I can’t change the settings for it. I accidentally made a typo on this.

+4
source share
5 answers

You can do this through delegates in C # :

 public static string MasterMethod(int param, Func<int,string> function) { return function(param); } // Call via: string result = MasterMethod(2, a => { if(a == 1) { return "if"; } else { return "else"; } }); 
+20
source

You can do this with anonymous delegates:

  delegate string CreateString(); public static void MasterMethod(CreateString fn) { string something = fn(); /*Do some big operation*/ } public static void StringSelection(int a) { if(a == 1) { return "if"; } else { return "else"; } } MasterMethod(delegate() { return StringSelection(2); }); 
+3
source
+2
source

Yes, use a delegate. These include lambda expressions and anonymous methods

+2
source

I think you are looking for a delegate.

+1
source

All Articles