Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return List<int> from an event

Tags:

c#

list

events

I have a custom delegate like this:

public delegate List<int> ExpandableChildrenGetterDelegate(string parentId);

and my event from this delegate is:

public event ExpandableChildrenGetterDelegate ExpandableChildrenGetting;

but Visual Studio designer cannot generate method for this action. And I must change my delegate to:

public delegate IEnumerable ExpandableChildrenGetterDelegate(string parentId);

How I can solve this, that I explicit write List<int> instead of IEnumerable?

like image 950
AliOsat Mostafavi Avatar asked Nov 23 '25 02:11

AliOsat Mostafavi


1 Answers

The problem here is that Visual Studio is trying to rationalize that there are N copies of List<int> that it needs to return from the event. One from every handler that receives the value. Hence it's defaulting to the C# 1.0 behavior of non-generic IEnumerable.

The best way to get this kind of information from an event is to make it a part of the EventArgs implementation. Then every handler can just append to it directly

class MyEventArgs : EventArgs {
  public List<int> ExpandableChildren = new List<int>();
}

public delegate void ExpandableChildrenGetterDelegate(
  string parentId, 
  MyEventArgs e);

The consumers of the event would just edit the list in the event args instead of returning a new one

like image 139
JaredPar Avatar answered Nov 24 '25 17:11

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!