Can I use a action to pass a value to a method parameter?

Viewed 47

I will try my best to explain what I am asking.

Imagine I have a Action in one class:

public Action Something;

And in another class I subscribe a method ot it with a parameter

private void Foo(int num)
{
    Debug.Log(num);
}

OneClass.Something += Foo;

So basically I want the parameter of Foo to be something that the OneClass Passes. Is that something that exists in C#?

1 Answers

Is this what you are trying to do:

public class Bar
{
    public event Action<int> Something;

    protected void OnSomething(int arg)
    {
        Something?.Invoke(arg);
    }
}


class Program
{
    static void Main(string[] args)
    {
        var bar = new Bar();

        bar.Something += Foo;
    }

    static void Foo(int x)
    {
        Debug.WriteLine(x);
    }
}

What I have above is an event .Something defined with an event handler of Action<int> function prototype. Action<T> represents methods of the form void f(T item).

Then I subscribe to the event with bar.Something += Foo

Finally, I define the method OnSomething() in order to allow the class Bar to trigger the event when needed.

Related