Programming Question: Ref and anonymous function
Closed this issue · 2 comments
Hey @PeturDarri
Thank you for this tool!
I have a programming question regarding subscription to the event:
in the start function, I call:
GenericEventBus.Instance.SubscribeTo(Handler);
then another method is subscribed:
private void Handler(ref RequestTryChangeStateEvent eventdata)
{
throw new NotImplementedException();
}
But I'd like to do that:
GenericEventBus<IEvent>.Instance.SubscribeTo<RequestTryChangeStateEvent>(ref args =>
{
var physicsState = args.RequestedPhysicsState;
TryChangePhysicsState(physicsState);
});
but I get an error on the args parameter, it says: "Parameter 'args' must be declared as 'ref'
I understand it's not possible to use the ref parameter in the anonymous function since this function manipulates the variable (which cannot be modified if is 'ref'). Can I use a similar syntax as I'd like, in this case?
Thank you!
When defining a ref
argument in a lambda, you must specify the type and wrap it in parenthesis:
GenericEventBus<IEvent>.Instance.SubscribeTo<RequestTryChangeStateEvent>((ref RequestTryChangeStateEvent args) =>
{
var physicsState = args.RequestedPhysicsState;
TryChangePhysicsState(physicsState);
});
Since the type is now specified in the argument, it no longer needs to be specified in the method call, so this can be simplified to:
GenericEventBus<IEvent>.Instance.SubscribeTo((ref RequestTryChangeStateEvent args) =>
{
var physicsState = args.RequestedPhysicsState;
TryChangePhysicsState(physicsState);
});
However, I would not recommend subscribing with anonymous functions, because it makes it impossible to unsubscribe unless you save and reuse the same instance in both calls. The only valid use case is if you know this event handler doesn't need to be unsubscribed.
Thank you so much for this explanation.