Is there some way to simplify the creation of a delegate for easier read coding? Here's an example of what I'd like to be able to do and I was wondering if there's a way to do it:
public delegate void MyDelegate(Object sender, EventArgs e);
public class ClassWithEvent
{
public event MyDelegate MyEvent;
public ClassWithEvent() { }
public void RegisterForEvent(Method)
{
MyEvent += new MyDelegate(Method);
}
public void Trigger()
{
if(MyEvent != null)
{
MyEvent(this, null);
}
}
}
public class ClassToRegister
{
public ClassWithEvent MyEventClass = new ClassWithEvent();
public ClassToRegister() { }
public void RegisterMe()
{
MyEventClass.RegisterForEvent(MyEventMethod);
MyEventClass.Trigger();
}
public void MyEventMethod(Object sender, EventArgs e)
{
Console.Writeline("Hello there!");
}
}
The point behind trying to attempt this is in the interest of encapsulation. I'm assuming that the class which fires the event is essentially a black box to classes accessing it. As this would be the most preferable Object-Oriented flow that I can see, I was wondering if there's a way to do this or if there's simply no way to do it without the registering class having some knowledge of the delegate it must create.
Yes, in the sense that you don't need a named delegate for this to work. Instead, you can use the generic delegate Action
(Action<object, EventArgs>
in your case). Action delegates return void, and have parameters matching the generic type argument.
Normally you would just expose the event directly (avoiding the "Register" function) and so wouldn't need to worry about that part of it anyways.
If you used it, your code would look like:
public class ClassWithEvent
{
public event Action<object, EventArgs> MyEvent;
public ClassWithEvent() { }
public void RegisterForEvent(Action<object, EventArgs> Method)
{
MyEvent += Method;
}
public void Trigger()
{
if(MyEvent != null)
{
MyEvent(this, null);
}
}
}
public class ClassToRegister
{
public ClassWithEvent MyEventClass = new ClassWithEvent();
public ClassToRegister() { }
public void RegisterMe()
{
MyEventClass.RegisterForEvent(MyEventMethod);
MyEventClass.Trigger();
}
public void MyEventMethod(Object sender, EventArgs e)
{
Console.Writeline("Hello there!");
}
}