Using delegate in CSharp example
Feb 24, 2013 00:00 · 332 words · 2 minute read
What is Delegate?
It is a special type in cSharp that reference method. You can subscribe methods with delegate and invoke them.
What is Syntax?
It is similar to method syntax that has delegate keyword. In order to subscribe a method to a delegate, both of them should have same “Input” and “Return” types.
delegate syntax
Public delegate void SomeDelegation(string message);
Example
We have a program that sends a message to the email and cell phone of our customers.
communication classes
public class Communication : ICommunication {
public void SendMessageWithEmail(string message) {
Console.WriteLine("send with email {0}", message);
// send message with email
}
public void SendMessageWithSms(string message) {
Console.WriteLine("send with sms {0}", message);
//send message with sms
}
}
Now Instead of sending the message with calling each method directly we can invoke them with delegate.
Define Delegate type
In this case we should define delegate that adopt to our communication type.
define delegate
private delegate void Sender(string message);
In other words, our delegate should have void return type with string input .
Register types
Then we should register desired communication. In this example I use the DelegateMethod constructor to register them.
Delegation
private readonly ICommunication _communication;
private readonly Sender _sender;
public DelegateMethod( Communication communication) {
_communication = communication;
_sender += _communication.SendMessageWithEmail;
_sender += _communication.SendMessageWithSms;
}
To register methods we add each method name without parentheses.
Invoke Delegate
Then we can invoke register methods with calling delegate.
invoke delegate
public void InvokeCommunication(string message) {
_sender(message);
}
Then it will call both Email and Sms communication and send the message .
Using it
Using delegate is similar to methods.
using delegation
var delegateMethod = new DelegateMethod(new Communication());
_message = "Test Message";
delegateMethod.InvokeCommunication(_message)
What will be happening?
The methods in ICommunication interface that register in the constructor will be subscribe to the delegate and when we call InvokeCommunication with desired message will be calling them in the same order.
Download
Feel free to download the full source code of this example from my GitHub.