Home > OS >  c# events vs List<Func<Args>>
c# events vs List<Func<Args>>

Time:03-13

is there any difference, e.g. less functional or in performance, memory, between using C# event vs a List<Func<MyArgs>>, the way I understand with an event I would call

obj.MyClickEvent  = handler;

while with the list

obj.MyOnClickFuncs.Add(clickFunc);

right now the List<Func<Args>> method just seems much simpler

CodePudding user response:

Events provide a more restrictive API for code wishing to subscribe to the events:

  • They can subscribe
  • They can unsubscribe

(In theory the underlying event concept provides a "raise" mechanism as well, but that's not implemented by C# events, and I suspect is effectively obsolete - I suspect because it violates the isolation described in this answer.)

They can't do anything else. For example, this would work with your "just expose a list" approach, but not with an event:

obj.MyOnClickFuncs.Clear();

Likewise with an event, subscribers don't get to call the handlers from other subscribers - whereas they can with the list approach.

In other words, events provide more isolation between subscribers. If you don't care about that isolation, then go ahead and expose a list. Personally I think the isolation is a good thing. There are plenty of things I don't like about events, but the isolation provided isn't one of them :)

  • Related