What is the correct / best way to declare a delegate

I noticed that most developers use the event for a callback, and I'm not sure if I am doing the right thing.

I noticed that most developer codes look like this:

public delegate void SampleDelegate(); public static event SampleDelegate SampleEvent; 

So far the "event" method looks 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 can explain to me what are the differences between both codes? Which way to do delegate is best practice? Is it better to set it as static?

+5
source share
1 answer

Look at your code:

 public delegate void SampleDelegate(); public SampleDelegate SampleEvent; 

This is not an event. Since 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(); } 

Alternatively, you can set it to a new value:

 public void TestMethod() { var a = new TestClass(); a.SampleEvent = null; } 

And this is not an event behavior. The interface cannot contain this "event":

 public interface ITestInterface { //TestClass.SampleDelegate SampleEvent; //does not compile } 

So, the right way is to add the word event 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 call it only 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 understand the difference between delegates and events. And choose the appropriate method for different situations: Events - when you need to assign other classes (one or more) about some changes. Delegetes - when you just want to declare a method signature and pass the implementation from the outside (simplified explanation).

+4
source

Source: https://habr.com/ru/post/1232878/


All Articles