views:

241

answers:

4

Events can only return void and recieve object sender/eventargs right?

If so then craptastic.... how can I pass a function pointer to another obj, like:

public bool ACallBackFunc(int n) 
{
    return n > 0;
}

public void RegisterCallback(Something s)
{
     s.GiveCallBack(this.ACallBackFunc);
}

Something::GiveCallBack(Action? funcPtr)

I tried using Action, but I need it to return some value and Actions can only return void. Also, we do not know what kind of a callback we will be recieving; it could return anything and have any params! Reflection will have to be used somehow I reckon.

A: 

I have written events that return a value, usually a bool. However, using Func will allow for return values.

dboarman
An example would clarify your meaning.
Robert Harvey
Func<> Seems that I need to know the return type ahead of time... we could be registering an unknown kind of function return value.
Jeff Dahmer
Try `Func<object[], object>`. That gets any number of arguments of any type (via the object array, like when using the `params` keyword) and returns an argument of any type.
Allon Guralnek
A: 

you need to create a delegate that passes back the classes that interest you

public delegate void CallbackDelegate(something s); public event CallbackDelegate myCallback

public void myFunction() { if (myCallback != null ) myCallback(new something()); }

check out msdn tutorial... http://msdn.microsoft.com/en-us/library/aa645739(VS.71).aspx

yamspog
A: 

Action by definition does not return value, you can use the generic version which allow multiple parameters.

If you want it to return value, use Func or if you just want it to return bool and take one argument, you can use Predicate

Or you can define a delegate anyway you like to return void or a value and take any number of argument. You can define a delegate like below and it is like a type that you can use. You can then pass it in as a callback parameter directly without using Action, Func or Predicate. Custom delegate is also use commonly use with writing custom multicast eventhandler.

public delegate double PerformAverageEventHandler(int val1, int val2, int val3);
Fadrian Sudaman
A: 

Perhaps you don't realize that an event is a multicast delegate allowing for multiple listeners to the event. This would leave you (potentially) with the need to receive more than one return value.

Some ideas to get around this are to pass a reference object to the event handler keeping a reference to the object. You could than have the result, but you would need another event to know when the object had been changed. But it would probably be a better idea to rethink whatever you are trying to accomplish. It sounds like a recipe for a stack overflow when you end up in a endless loop of the event causing a change that then raises the event.

Kirk