Some Creativity

Weblog of Siddharth Uppal

Archive for April 14th, 2008

Raising events from structures

with 3 comments

Problem:

Do warning bells go off in your head when you see code like the following?


struct SomeStruct
{
    // some code here
    public event EventHandler< EventArgs > SomeEvent;
    // some more code here

    public void DoSomething()
    {
        // some code here
        if (SomeEvent != null)
            SomeEvent(this, EventArgs.Empty);
    }
}

Are there any problems you need to be aware of when declaring events inside structures?

Solution:

Well, code like the following wouldn’t work, even though it seems to be perfectly reasonable. foo_SomeEvent will actually never be called.


        public void HookOntoEvent(SomeStruct foo)
        {
            foo.SomeEvent += new EventHandler(foo_SomeEvent);
        }

        void foo_SomeEvent(object sender, EventArgs e)
        {
            // code to handle event here
        }

Why? Remember struct is a value-type. Consequently, foo in HookOntoEvent would be initialized with a copy of the actual SomeStruct object which was passed to it by the caller. So the method would only be hooking up foo_SomeEvent method to this copy of the object which will go out of scope as soon as the HookOntoEvent is done executing. As a result, foo_SomeEvent will never be called.

Be careful when mixing structures and events. I personally stay away from raising events from structures.

Written by Sid

April 14th, 2008 at 8:12 pm

Posted in .NET, General

Tagged with , ,