I have an event broker that exposes an EventHandler<T>
that allows observers to inspect the event argument and, if needed, modify it. While this works okay, I would ideally like to ensure that T
only lives on the stack and, furthermore, that no component is able to take a reference to T, thereby extending its lifetime.
public class Game // mediator pattern
{
public event EventHandler<Query> Queries; // effectively a chain
public void PerformQuery(object sender, Query q)
{
Queries?.Invoke(sender, q);
}
}
Sadly, a ref struct
cannot be used as a generic argument:
ref struct Query {} // EventHandler<Query> not allowed
And similarly I cannot imbue EventHandler
's TEventArgs
with any sort of 'use structs, pass by reference' mechanics.
Now, in C#, we can decide whether variables live on the stack on the heap, e.g. with stackalloc
and such, so what I'm after, I guess, is just a way of getting something equivalent to a ref struct
inside an event.