Search This Blog

Wednesday, November 23, 2011

C#–Never place an event inside a struct; C# event is always null inside a struct

When you write something similar to:

namespace XXX
{   
    public struct SomeStruct
    {
        public event SomeDelegate SortDirectionChanged;
    }

    public delegate void SomeDelegate(SomeInfo input);
}
   

then SortDirectionChanged event will always be null.
So when you try to set a delegate to the event like this:

var sth = new SomeStruct();
sth.SortDirectionChanged += SomeMethodServingEventCall;

SortDirectionChanged will be null when you'll try to pass on the struct. (when you check it with a debugger right after the assignment it will appear to be ok – strange). Use class instead.

2 comments:

  1. Yes. Was pretty surprised with this behavior.

    Possible reason is that event is an immutable ref type, so it can not be modified -- only a new copy may be created. And when in a struct... voila.

    ReplyDelete
  2. The reason is that structs are passed by value, so whenever you pass a struct around you are looking at a copy of the original instance. The backing event field actually gets updated and that's why you see it inside the debugger, but the whole struct is a copy.

    ReplyDelete

If you like this post, please leave a comment :)