Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to send an Object's Method to a Function?

I am wondering if it is possible (and what the syntax would be) to send an object's method to a function.

Example:

Object "myObject" has two methods "method1" and "method2"

I would like to have a function along the lines of:

public bool myFunc(var methodOnObject)
{
   [code here]
   var returnVal = [run methodOnObject here]
   [code here]
   return returnVal;
}

So that in another function I could do something like

public void overallFunction()
{
   var myObject = new ObjectItem();
   var method1Success = myFunc(myObject.method1);
   var method2Success = myFunc(myObject.method2);
}
like image 581
ChrisHDog Avatar asked Dec 06 '25 17:12

ChrisHDog


1 Answers

Yes, you need to use a delegate. Delegates are fairly analogous to function pointers in C/C++.

You'll first need to declare the signature of the delegate. Say I have this function:

private int DoSomething(string data)
{
    return -1;
}

The delegate declaration would be...

public delegate int MyDelegate(string data);

You could then declare myFunc in this way..

public bool myFunc(MyDelegate methodOnObject)
{
    [code here]
    int returnValue = methodOnObject("foo");
    [code here]
    return returnValue;
}

You can then call it in one of two ways:

myFunc(new MyDelegate(DoSomething));

Or, in C# 3.0 and later, you can use the shorthand of...

myFunc(DoSomething); 

(It just wraps the provided function in the default constructor for that delegate automatically. The calls are functionally identical).

If you don't care to actually create a delegate or actual function implementation for simple expressions, the following will work in C# 3.0 as well:

public bool myFunc(Func<string, int> expr)
{
    [code here]
    int returnValue = methodOnObject("foo");
    [code here]
    return returnValue;
}

Which could then be called like so:

myFunc(s => return -1);
like image 153
Adam Robinson Avatar answered Dec 08 '25 07:12

Adam Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!