I am trying to properly check if an object's event has already been set to a specific method.
That stackoverflow question offers 2 solutions :
- a quick and dirty one which simply unregisters the method and registers it again.
- a more proper one which checks if the delegate to the method has been added.
I have several questions related to the second solution. Let's assume the following code
public static class Util
{
public static bool IsRegistered<T>(this EventHandler<T> handler, Delegate prospectiveHandler)
=> handler != null
&& handler.GetInvocationList().Any(existingHandler => existingHandler == prospectiveHandler));
}
public class Object1
{
public event EventHandler<string> OnSomething;
public bool CheckOnSomething(Delegate handler) => this.OnSomething.IsRegistered(handler);
}
public class Object2
{
private Object1 o;
public Object2(Object1 o1)
{
this.o = o1;
}
public void CatchSomething(object sender, string something)
{
// ...
}
public void HookToSomething()
{
if (!o.CheckOnSomething( ??? ))
o.OnSomething += this.CatchSomething;
}
}
- In order to call
CheckOnSomething, i need to pass a delegate toCatchSomething. Do i have to define a new delegate for that, or is there already something i can use ? - If i define a new delegate, will the delegate equality work ? The documentation says it checks for the delegate type, but since i pass the method directly, isn't a new delegate type created on the fly, which would make the equality always return
false?