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 {
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();
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).
source share