.NET already has a delegate that does not receive any parameters, this is Action
So you have an animation class:
public class Animation { public event Action OnEnd; }
But you can pass events as parameters if you try to get this compilation error
An event can only appear on the left side + = or - = "
So, let's create an interface and declare an event there
public interface IAnimation { event Action OnEnd; }
Using the interface approach, you do not have external dependencies, and you can have many classes that implement it, it is also good practice, depends on abstractions instead of specific types. There is an abbreviation SOLID, which explains 5 principles for improving OO code.
And then your animation class implements that
Designation: CallEnd method is for testing only.
public class Animation : IAnimation { public event Action OnEnd; public void CallEnd() { OnEnd(); } }
And now you WaitForDelegate will get IAnimation , so the class can handle any class that implements the IAnimation class
public class WaitForDelegate<T> where T : IAnimation { public WaitForDelegate(T animation) { animation.OnEnd += () => { Console.WriteLine("trigger"); }; } }
Then we can test the code we made with the following code
public static void Main(string[] args) { var a = new Animation(); var waitForDelegate = new WaitForDelegate<IAnimation>(a); a.CallEnd(); }
Result
trigger
Here is the working version on dotnetfiddle
https://dotnetfiddle.net/1mejBL
Important tip
If you are working with multithread, you should take some precaution to avoid a Null Reference Exception
Look again at the CallEnd method that I added for testing
public void CallEnd() { OnEnd(); }
The OnEnd event may not matter, and then if you try to raise it, you will get a Null Reference Exception.
So, if you use C # 5 or below, do something like this
public void CallEnd() { var @event = OnEnd; if (@event != null) @event(); }
With C # 6 it could be like
public void CallEnd() => OnEnd?.Invoke();
More explanation, you could have this code
public void CallEnd() { if (OnEnd != null) OnEnd(); }
This code, which is above, will probably make you think that you are safe from a Null Reference Exception, but with a multi-threaded solution, you are not. This is because the OnEnd event can be set to zero between the execution if (OnEnd != null) and OnEnd();
There is a good article by John Skeet about this, you cannot see Clear an event handler call using C # 6