Ygnas
Ygnas

Reputation: 145

Which is the right way to use delegate?

I would like two know if there is a difference between the two, and if they are the same which one is the better practice?

Class one:

Action onDeath;
public void RegisterDeath(Action callback) 
{
    onDeath += callback;
}

And then let other class 2 to subscribe to this RegisterDeath method? Or is it better to make:

public Action onDeath;
//or even
public event Action onDeath;

And subscribe to this public delegade without clutter in the main class? If there is a difference could someone explain it briefly

Upvotes: 2

Views: 71

Answers (1)

adjan
adjan

Reputation: 13652

If you publicly expose a delegate, everyone can reset the invocation list or even invoke the delegate:

class Test
{
    public static Action MyAction;
}

Test.MyAction = () => Console.WriteLine("Hello"); // Resets invocation list
Test.MyAction(); // Invokes delegate

In most cases, this is unwanted behavior. That's why C# has the event keyword. Events can only be subscribed (using +=) or unsubscribed (using -=).

class Test
{
    public static event Action MyAction;
}

Test.MyAction = () => Console.WriteLine("Hello"); // Not allowed
Test.MyAction(); // Not allowed
Test.MyAction += () => Console.WriteLine("Hello"); // Only this is allowed

Using your own method RegisterDeath could give you even more control of how or when the delegate can be (un)subscribed. In many cases, a simple event should be sufficient, though.

Upvotes: 7

Related Questions