C# event semantics

Try to answer this without Google.   CLINQ has to deal with similar semantics now, and the result is possibly surprising.

What is the output to the console for each test when run individually? I’ll post the answer in a couple of days.

        public event Action<int> TestEvent;

        [Test]
        public void SubscribeDuringAnEventTest()
        {
            Action<int> subscribedDuringFiring = (arg) =>
            {
                Console.WriteLine("subscribedDuringFiring " + arg);
            };

            Action<int> subscribeAction = (arg) =>
            {
                Console.WriteLine("subscribeAction " + arg);
                if (arg == 0)
                    TestEvent += subscribedDuringFiring;
            };

            Action<int> refire = (arg) =>
            {
                Console.WriteLine("refire " + arg);
                if (arg == 0)
                    TestEvent(1);
            };

            TestEvent += subscribeAction;
            TestEvent += refire;
            
            TestEvent(0);
        }

        [Test]
        public void UnsubscribeDuringAnEventTest()
        {
            Action<int> unsubscribedDuringFiring = (arg) =>
            {
                Console.WriteLine("unsubscribedDuringFiring " + arg);
            };

            Action<int> unsubscribeAction = (arg) =>
            {
                Console.WriteLine("unsubscribeAction " + arg);
                if (arg == 0)
                    TestEvent -= unsubscribedDuringFiring;
            };

            Action<int> refire = (arg) =>
            {
                Console.WriteLine("refire " + arg);
                if (arg == 0)
                    TestEvent(1);
            };

            TestEvent += unsubscribeAction;
            TestEvent += unsubscribedDuringFiring;
            TestEvent += refire;

            TestEvent(0);
        }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s