Skip to end of metadata
Go to start of metadata

You can, indeed, store functions to variables and pass in functions as arguments in C#. These can both be done using delegates.

Storing function:
In my code,
Func<string, string> methodVar = storedFunc
is where I declare a variable called methodVar that can store functions that take in a string and return a string. The first "string" is where we put the argument type(s), and the second is where we put the return type(s). We have a function called storedFunc that we call through methodVar on a variable. In this program, I have a string called name, so I use methodVar(name) to use the stored function.

Function as argument:
First, I declared a masterMethod upper function. This is where I define the method and specify the kinds of functions that can be passed in as arguments. Then I declared and defined the two submethods, and in my main function I just called masterMethod with the two sub-methods passed in as arguments. In this case, the master method runs both sub-methods on the input strings. Then it returns a string that shows the results put together.

So the function types in C# are called "delegates".

  • No labels