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.

4 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


  3. It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article. Dot Net Training in chennai | Dot Net Training in velachery

    ReplyDelete
  4. C#–Never place an event inside a struct; C# event is always null inside a struct.perfect explanation in it.thanks for your valuable information. dot net training in velachery | dot net training in chennai

    ReplyDelete

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