I find a lot of resources on how to react on an Event (or delegate). For example:
Control.ValueChanged += (sender, e) =>
{
//do something
};
However, I don't find how I can create my own Event? Basically I have a class that needs to 'fire' an event and in the class that creates this object you can react on this Event.
Any idea?
If I would do it with a Delegate instead, how should I do that (creating my own Delegate object that can be implemented by another class)?
Thanks!
You mean something like this?
class Foo
{
public event EventHandler MyEvent;
public void DoSomething()
{
// do stuff
// raise the MyEvent event
var handler = MyEvent;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
I personally use Action
s.
public abstract class ServiceClient
{
public Action OnNetworkActivityStarted { get; set; }
private void StartNetworkActivity()
{
if (OnNetworkActivityStarted != null)
OnNetworkActivityStarted();
}
}
Any inheriting class would/could use the logic you have provided above.
public class MyClient : ServiceClient
{
public MyClient()
{
this.OnNetworkActivityStarted += () =>
{
//do whatever the subclass needs to do when the event is fired
};
}
}
I have this implemented in class-library I plan on using for cross-platform mobile apps. This allows each device to implement their own strategy for letting the user know that network has started.
I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With