Search code examples
c#eventsdelegatesaction

How to link two delegates in different classes?


I have two different classes, say Outer and Inner. An instance of Inner is a field in the Outer. My goal is to link the ActionInner and ActionOuter; in other words, when I add an action for ActionOuter, I want it to be added to ActionInner. How can I do it?

Here is my attempt that does not work, because both actions are nulls:

    class Program
    {
        static void Main()
        {
            Outer outer = new Outer();

            void writeToConsole(double foo)
            {
                Console.WriteLine(foo);
            }

            // Here I expect to link the 'writeToConsole' action to 'inner' 'ActionInner'
            outer.ActionOuter += writeToConsole;

            // Here I expect an instance of 'inner' to output '12.34' in console
            outer.StartAction();

            Console.ReadKey();
        }
    }

    class Inner
    {
        public Action<double> ActionInner;

        public void DoSomeStuff(double foo)
        {
            ActionInner?.Invoke(foo);
        }
    }

    class Outer
    {
        readonly Inner inner;

        public Action<double> ActionOuter;

        public void StartAction()
        {
            inner.DoSomeStuff(12.34);
        }

        public Outer()
        {
            inner = new Inner();

            // Here I want to somehow make a link between two actions
            inner.ActionInner += ActionOuter;
        }
    }

Solution

  • Change ActionOuter fields to property. Set and get like below;

    public Action<double> ActionOuter
        {
            set => inner.ActionInner = value;
            get => inner.ActionInner;
        }