Partial events #8064
-
At the moment, events cannot be declared My specific use case is to make a generator for weak events (i.e. events that only keep weak references to the handlers). I have a library that provides a generic weak event implementation. At the moment the library has certain restrictions (not relevant to this discussion, but you can look at the issue if you're interested), which could probably be solved by using a source generator. Ideally I'd like the user to declare an event like this: public delegate void MyEventHandler(int foo, string bar);
public partial class MyClass
{
[WeakEvent]
public partial event MyEventHandler MyEvent;
} And the library would generate the event implementation, and a method to raise the event. In my use case it would probably similar to this: partial class MyClass
{
private readonly __WeakMyEventHandler _myEvent; // __WeakMyEventHandler would also be generated
public partial event MyEventHandler MyEvent
{
add { _myEvent.AddHandler(value); }
remove { _myEvent.RemoveHandler(value); }
}
protected void RaiseMyEvent(int foo, string bar) => _myEvent.Invoke(foo, bar);
} But since events can't be partial, it's not currently possible to use this approach. This idea is actually pretty similar to the Partial properties proposal, which wants to allow partial properties to allow code generation scenarios. Like for properties, it would be required to have an implementing declaration of the event (whether it's provided manually or by a generator). |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 12 replies
-
One thing that I think would need consideration is how the declaring class would be expected to raise the event. |
Beta Was this translation helpful? Give feedback.
-
Could you please include a full sample of the implementation part you would like to generate for the partial event, and how the event would be used in user code? Thanks! |
Beta Was this translation helpful? Give feedback.
-
Created a proposal for this: https://github.com/dotnet/csharplang/blob/main/proposals/partial-events-and-constructors.md |
Beta Was this translation helpful? Give feedback.
-
Is there any chance this proposal would include partial enums as well? My use-case is kinda simple, often times I require to have helper/special members declared (e.g. AllFlags, Max) to ease up working with the enumerations. Nowadays we can get a lot of stuff done via source generator to make enums rather pleasant via extension methods, It would be really cool if we could just source-generate these as well directly on the enumeration to make it feel more natural. |
Beta Was this translation helpful? Give feedback.
Created a proposal for this: https://github.com/dotnet/csharplang/blob/main/proposals/partial-events-and-constructors.md
Champion issue: #9058