Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing a function in a variable?

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?

like image 747
Steffan Donal Avatar asked Dec 19 '10 23:12

Steffan Donal


People also ask

How do you call a function inside a variable?

we put the function in a variable if inside the function block we use the return method: var multiplyTwo = function (a) { return a * 2; }; if we simply call this function, nothing will be printed, although nothing is wrong with the writing of the function itself.

How do you reference a function?

To pass a value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to, by their arguments.

How do you pass the reference of a variable in a function as parameter?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.

How do you assign a function to a variable?

Method 1: Assign Function Object to New Variable Name A simple way to accomplish the task is to create a new variable name g and assign the function object f to the new variable with the statement f = g.


3 Answers

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

like image 166
David Avatar answered Oct 07 '22 01:10

David


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);
like image 42
Bablo Avatar answered Oct 07 '22 00:10

Bablo


Are you looking for Delegates?

like image 30
Sonny Saluja Avatar answered Oct 07 '22 00:10

Sonny Saluja