I noticed most of the developers are using event for callback and I'm not sure whether I'm doing in a right way.
I noticed most of developers' codes look like this:
public delegate void SampleDelegate();
public static event SampleDelegate SampleEvent;
While the way I do "event" look like this:
public delegate void SampleDelegate();
public SampleDelegate SampleEvent; // notice that I didn't set to static and not an event type
I hope someone could explain to me what's the differences between both codes? Which way of doing delegate is a better practice? Is it better to set it as a static?
Let's look at your code:
public delegate void SampleDelegate();
public SampleDelegate SampleEvent;
It's not an event. Because you can call SampleEvent outside the containing class:
public class TestClass
{
public delegate void SampleDelegate();
public SampleDelegate SampleEvent;
}
public void TestMethod()
{
var a = new TestClass();
a.SampleEvent();
}
Also, you can set it to new value:
public void TestMethod()
{
var a = new TestClass();
a.SampleEvent = null;
}
And this is not the event behavior. An interface can not contain this "event":
public interface ITestInterface
{
//TestClass.SampleDelegate SampleEvent; //does not compile
}
So the right way - to add event
word for real events:
public class TestClass : ITestInterface
{
public delegate void SampleDelegate();
public event SampleDelegate SampleEvent;
private void FireEvent()
{
var handler = SampleEvent;
if (handler != null)
handler();
}
}
public interface ITestInterface
{
event TestClass.SampleDelegate SampleEvent;
}
And now you can only call it from the containing class:
public void TestMethod()
{
var a = new TestClass();
//a.SampleEvent(); //does not compile
a.SampleEvent += A_SampleEvent; //subscribe to event
}
private void A_SampleEvent()
{
Console.Write("Fired"); //fired when FireEvent method called
}
So, you must uderstand difference between delegates and events. And choose the appropriate way for different situations: Events - when you need to nodify other classes (one or more) about some changes. Delegetes - when you just want to declare a method signature and pass the implementation from outside (simplified explanation).
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