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.

9 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
  5. Well, if you want to put an event in a struct you can do it like this: public event TypedEventHandler MyEvent { add {...} remove {...} } and then private List> handlers;

    ReplyDelete
    Replies
    1. Sorry, forgot the html. It's TypedEventHandler<TSource,TEventArgs>.

      Delete
  6. Great Blog to read,Its gives more useful information. Thanks for sharing.
    Selenium Training in Chennai

    ReplyDelete
  7. view website best replica bags online find more information Chloe Dolabuy you can find out more https://www.dolabuy.ru/

    ReplyDelete

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