Post

Raising events from structures

In .NET, General on April 14, 2008 by Sid Tagged: , ,

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.


3 Responses to “Raising events from structures”

  1. Its kind of surprising that its even allowed, seeing as this is the result.

  2. Good tip.

    Although not always the case, it is useful to think cautiously when using structures and events together. In some cases, particularly for very lightweight structures (shouldn’t all be?), an event can be useful. In these rare situations, care should be used. For example, the real problem in the sample code is the missing ‘ref’ to ensure that HookOntoEvent receives a reference to the SomeStruct instance, rather than a copy of the structure. Of course, if the structure is quite large then consideration should be made to using a class instead.

  3. @BlackWasp:

    Thanks.

    I should have mentioned about “ref” in the post for completeness. Caution while mixing structures and events – is the point I wanted to make.

Leave a Reply