Thrindil
Thrindil

Reputation: 143

Subscribing to event inside a method while passing extra parameters from this method without using a lambda expression

So I have an event signature like this:

public event EventHandler<OnColorChangedEventArgs> onColorChanged;

public class OnColorChangedEventArgs : EventArgs
{
    public Color color;
}

and a method I want to subscribe to the event like this:

private void UpdateColor(object sender, RayCaster.OnColorChangedEventArgs eventArgs, PositionOnLine positionOnLine)
{
    if (positionOnLine == PositionOnLine.Start)
    {
        _lineRenderer.startColor = eventArgs.color;
    }
    else
    {
        _lineRenderer.endColor = eventArgs.color;
    }
}

As you can see, the subscribing method requires more parameters than the event invocation passes. Those extra parameters should be passed from a method I call to subscribe to the event in the first place, like this:

public void AddPoint(RayCaster rayCaster, PositionOnLine positionOnLine, Transform transform)
{
    //some irrelevant code

    rayCaster.onColorChanged += (sender, args) => UpdateColor(sender, args, positionOnLine);
}

This works as I want it to. However, as far as I understand it, this is an anonymous delegate. And I need to unsubscribe from this method at some point. I can't seem to find a way to turn this into a non-anonymous delegate. I'm pretty new to delegates and events, so please point out any code smells. Thank you.

Upvotes: 2

Views: 1184

Answers (2)

JohnnyPrognose
JohnnyPrognose

Reputation: 51

You could use a local function like this:

public void AddPoint(RayCaster rayCaster, PositionOnLine positionOnLine, Transform transform)
{
    //some irrelevant code

    void updateColor(object sender, OnColorChangedEventArgs e)
    {
        UpdateColor(sender, e, positionOnLine);
    }

    rayCaster.onColorChanged += updateColor;
    rayCaster.onColorChanged -= updateColor;
}

By the way: The event should not be named like on..., but just e.g. ColorChanged.

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1064104

The delegate signature must match, so: you can't cheat here. If you genuinely need to unsubscribe later, you can store the delegate instance somewhere, i.e.

EventHandler<OnColorChangedEventArgs> handler = (sender, args) =>
     UpdateColor(sender, args, positionOnLine);
rayCaster.onColorChanged += handler;
// ... and later
rayCaster.onColorChanged -= handler;

Upvotes: 5

Related Questions