9

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 was a function. EG. 'bar(foobar)'.

How?

Steffan Donal
  • 2,244
  • 4
  • 24
  • 47

4 Answers4

23

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).

David
  • 208,112
  • 36
  • 198
  • 279
  • I guess I could do that. But then I'd be locked to having a max of 4 parameters, if I were to use the Func<> method, which would be preferred. I could probably get by using this, but it would be nice if I could get around the limit. – Steffan Donal Dec 19 '10 at 23:42
  • @Ruirize: Interesting, I've never run into that limit before so I guess I've never known about it. Looks like it's been covered here before, though, so something we should both take a look at: http://stackoverflow.com/questions/3582866/func-for-5-arguments – David Dec 19 '10 at 23:44
  • That sounds great! Although, if I do have to make many of these for each unit, I'll probably just use my Lua interpreter. – Steffan Donal Dec 19 '10 at 23:48
  • 1
    If the assumption here is that in .Net 3.5 you're limited to Func<...T4,TResult>, then install Reactive Extensions to get definitions up to Func<...T16,TResult> (which is what .Net 4 also offers) – spender Dec 19 '10 at 23:50
2

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);
Bablo
  • 906
  • 7
  • 18
1

Are you looking for Delegates?

Sonny Saluja
  • 7,193
  • 2
  • 25
  • 39
0

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.

BurnsBA
  • 4,347
  • 27
  • 39
Jon
  • 428,835
  • 81
  • 738
  • 806