Delegates, Why

When & why to use delegates?

I agree with everything that is said already, just trying to put some other words on it.

A delegate can be seen as a placeholder for a/some method(s).

By defining a delegate, you are saying to the user of your class, "Please feel free to assign any method that matches this signature to the delegate and it will be called each time my delegate is called".

Typical use is of course events. All the OnEventX delegate to the methods the user defines.

Delegates are useful to offer to the user of your objects some ability to customize their behavior.
Most of the time, you can use other ways to achieve the same purpose and I do not believe you can ever be forced to create delegates. It is just the easiest way in some situations to get the thing done.

Why do we need C# delegates

Of course you can call method directly on the object but consider following scenarios:

  1. You want to call series of method by using single delegate without writing lot of method calls.
  2. You want to implement event based system elegantly.
  3. You want to call two methods same in signature but reside in different classes.
  4. You want to pass method as a parameter.
  5. You don't want to write lot of polymorphic code like in LINQ , you can provide lot of implementation to the Select method.

When would you use delegates in C#?

Now that we have lambda expressions and anonymous methods in C#, I use delegates much more. In C# 1, where you always had to have a separate method to implement the logic, using a delegate often didn't make sense. These days I use delegates for:

  • Event handlers (for GUI and more)
  • Starting threads
  • Callbacks (e.g. for async APIs)
  • LINQ and similar (List.Find etc)
  • Anywhere else where I want to effectively apply "template" code with some specialized logic inside (where the delegate provides the specialization)

The purpose of delegates

Yeah,

You're almost there. A delegate refers to a method or function to be called. .NET uses the Events to say.. when someones presses this button, I want you to execute this piece of code.

For example, in the use of a GPS application:

public delegate void PositionReceivedEventHandler(double latitude, double longitude);

This says that the method must take two doubles as the inputs, and return void. When we come to defining an event:

public event PositionReceivedEventHandler PositionReceived;  

This means that the PositionRecieved event, calls a method with the same definition as the
PositionReceivedEventHandler delegate we defined. So when you do

PositionRecieved += new PositionReceivedEventHandler(method_Name);

The method_Name must match the delegate, so that we know how to execute the method, what parameters it's expecting. If you use a Visual Studio designer to add some events to a button for example, it will all work on a delegate expecting an object and an EventArgs parameter.

Hope that helps some...

Why this multicast delegation isn’t working with functions in C#?

According to the spec:

If the delegate invocation includes output parameters or a return value, their final value will come from the invocation of the last delegate in the list.

If you need more control over individual results, then use GetInvocationList():

foreach (MyDlgt myDlgt in MultiCast.GetInvocationList())
{
double result = myDlgt(NUM1, NUM2);
}

Why to use delegates in .Net

A delegate is a way to have a reference to a particular method as a variable, meaning it can change, instead of as your last example, hardcoding into the program which methods to call.

Are there way to do this without delegates? Sure, you can provide objects that override methods or use classes that implements interfaces, but delegates are cheaper in the sense that you don't need a whole type wrapped around the single method.

Examples of situations where hardcoding won't do, and interfaces/overriding methods would be more work than delegates, try looking at visual components and their events. Events in .NET use delegates. You can simply double-click on a button in the visual designer in Visual Studio and it will create the method for you and wire it up to the event by the way of a delegate. Having to create a class, or implement an interface on top of the form class would be a lot more work, and especially if you have multiple buttons that you would want to do different things, then you definitely need multiple objects implementing those interfaces.

So delegates have their place, but your examples doesn't do them justice.

Here is a LINQPad example that demonstrates that one method (DoSomething) can end up doing different things depending on the delegate provided to it:

void Main()
{
DoSomething(msg => Console.WriteLine(msg));

using (var writer = new StreamWriter(@"d:\temp\test.txt"))
{
DoSomething(msg => writer.WriteLine(msg));
}
}

public delegate void LogDelegate(string message);

public static void DoSomething(LogDelegate logger)
{
logger("Starting");
for (int index = 0; index < 10; index++)
logger("Processing element #" + index);
logger("Finishing");
}

This will first log to the console, then rerun the method and log to a file.

Since we have multicast delegates, why do we need events?

Couple of reasons why we need events:

  • Restricting scope, you do not want to expose your events, like you can for your delegates.
  • You can have events as fields in your interfaces and not delegates

Example below:

Class Printer
{
public event EventHandler Print;

public void Start()
{
OnPrint();
}

protected virtual void OnPrint()
{
Print?.Invoke(this,EventArgs.Empty);
}
}
class Program
{
static void Main(string[] args)
{
//When Print is an EventHander
var printer = new Printer();
printer.Print += PrintEvent;
printer.Start();

//If Print was a delegate this is possible, else you get compile time errors
printer.Print(null,null); // Events will not allow to have a direct invoke
printer.Print = null; //You cannot assign a null to an Event Handler
}
private static void PrintEvent(object sender, EventArgs e)
{
System.Console.WriteLine("Printing event");
}
}

Why do Events need Delegates? Why do we even Need Events?

but enough to know that delegate datatype is a single cast delegate. delegate void is a multicast delegate - a list of references to methods.

Not true. All "normal" delegates are multicast, even if they have a non void return type.

Question 1: I think myObject is the target, and SomeMethod is the method to reference, but I'm only passing one input. So is myObject.SomeMethod compiled to a string and is the string split by the period? Ridiculous I know.

No, myObject.SomeMethod is a method group. This way of delegate instance creation involves a bit of compiler magic.

multicastdelegate+=newmethodtobereference

If multicastdelegate is a normal delegate variable, this is equivalent to multicastdelegate = multicastdelegate + newmethodtobereference i.e. it creates a new delegate that calls several methods, and assigns it to multicastdelegate.


Now to your main question: What's the purpose of events?

Events have delegate types. They behave similarly to properties. Their purpose is encapsulation, in particular they only allow consumers to subscribe(+=) and unsubscribe(-=) but not to read the value of the event.

Properties are a combination of two methods: get and set.

Events are a combination of two public methods subscribe and unsubscribe, and in the case of a field-like event also something similar to a private getter.



Related Topics



Leave a reply



Submit