Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the correct/better way of Delegate declaration

Tags:

c#

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?

like image 325
Cadrick Loh Avatar asked Sep 26 '22 14:09

Cadrick Loh


1 Answers

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).

like image 105
Backs Avatar answered Oct 03 '22 15:10

Backs