What I am trying to achieve is to create convenient syntax for calling a callback on an event only once.
public static class Extensions
{
public static void Once<T>(this EventHandler<T> @event, EventHandler<T> callback)
{
EventHandler<T> cb = null;
cb = (object that, T info) => {
if (callback != null) {
callback(that, info);
}
@event -= cb;
};
@event += cb;
}
}
This should allow us to write something like this:
obj.OnSomething.Once((sender, obj) => Console.WriteLine(obj));
Note that OnSomething is an event EventHandler of some type.
The problem is that I get the error message:
Error CS0070: The event
SharpTox.Core.Tox.OnFriendMessage' can only appear on the left hand side of += or -= when used outside of the type
SharpTox.Core.Tox' (CS0070) (SharpTox.Tests)
Is there no way to achieve this that easily? Do I have to remove event from OnSomething and make it a simple delegate?