Say I have a function. I wish to add a reference to this function in a variable.
So I could call the function \'foo(bool foobar)\' from a variable \'bar\', as if it
Are you looking for Delegates?
It sounds like you want to save a Func
to a variable for later use. Take a look at the examples here:
using System;
public class GenericFunc
{
public static void Main()
{
// Instantiate delegate to reference UppercaseString method
Func<string, string> convertMethod = UppercaseString;
string name = "Dakota";
// Use delegate instance to call UppercaseString method
Console.WriteLine(convertMethod(name));
}
private static string UppercaseString(string inputString)
{
return inputString.ToUpper();
}
}
See how the method UppercaseString
is saved to a variable called convertMethod
which can then later be called: convertMethod(name)
.
Using delegates
void Foo(bool foobar)
{
/* method implementation */
}
using Action
delegate
Public Action<bool> Bar;
Bar = Foo;
Call the function;
bool foobar = true;
Bar(foobar);
You need to know the signature of the function, and create a delegate.
There are ready-made delegates for functions that return a value and for functions that have a void return type. Both of the previous links point to generic types that can take up to 15 or so type arguments (thus can serve for functions taking up to that many arguments).
If you intend to use references to functions in a scope larger than a local scope, you can consider defining your own custom delegates. But most of the time, Action
and Func
do very nicely.
Update:
Take a look at this question regarding the choice between defining your own delegates or not.