Is it possible in C# to pass a delegate or event to a method so that the method can assign a new event handler to that delegate with += (and not so that the method can call the delegate)?
Lets say I can mix C++ with C#. This would be what I’m looking for:
public class MyClass
{
public Action* actionPtr;
public void Assign(Action* action)
{
actionPtr = action;
(*action) += SomeMethod;
}
public void Unassign()
{
(*action) -= SomeMethod;
}
void SomeMethod()
{
// Do stuff
}
}
Hope it makes sense.
Event: no (unless you’re in the class where the event is defined). This is enforced by the C# compiler.
Plain old delegate: yes. Pass it as a
refparameter.(Think about it this way: how do you add a handler to a delegate? You use
+=, right? That is an assignment operator, which is static: you are assigning the delegate to a new delegate instance that includes the method specified to the right of the+=, just likex += 1assignsxtox + 1. The only time you can ever assign an external variable to a new value or object from within a method is when it was passed as areforoutparameter).For example, the following code leaves
listuntouched:The following would assign it to a new
List<int>:It’s the same principle.