Delegates

Syntax: delegate void LogWriter(String logString);

MultiCast Delegate

Syntax:

LogWriter writeToAll = null;
writeToAll += writeToConsole;
writeToAll += writeToFile;
writeToAll += writeToPdf;
writeToAll += writeToPdf;
writeToAll += writeToPdf;
writeToAll -= writeToPdf;
// notice the dropping of the event

LogWriter lw = new Program().WriteToAllWriter;
lw(
“Hello World!”);

Output:

writeToConsole: Hello World!

writeToFile: Hello World!

writeToPdf: Hello World!

writeToPdf: Hello World!

Generic Delegates

Syntax: public delegate void GenericLogWriter<T>(T logString);

Usage:

GenericLogWriter<String> writeToAll = null;
writeToAll += writeToConsole;

Func and Action – Library Defined Delegates

Action’s input from zero to 16, output is void

Func’s input from zero to 16, output is a generic type

Syntax:

Action<String> writeToAll = null;
writeToAll += writeToConsole;

Delegate Target

If the delegates’ method is not static, the target will refer to the instance to whom the method belongs.

Syntax:

LogWriter lw = new Program().WriteToAllWriter;
Console.WriteLine(lw.Target);

Covariance and Contravariance

Contravariance: Delegate has a more specific parameter type than its method:

Syntax:

Delegate: delegate void LogWriter(String logString);
Method: private void writeObjectToFile(Object logString)

Usage:

LogWriter writeToAll = null;
writeToAll += writeObjectToFile;

Covariance: Method return type can be more specific to the assignee type. i.e, Polymorphism allow assigning a string to an object. for the same reason. when delegate receive the string result from the called method, it will be upcasted to object. the next syntax demonstrate that:

Syntax:

Delegate: delegate Object LogEncoders(String logString);
Method: String encodeLog(String logString)

Usage:

LogEncoders le = null;
le += encodeLog;

Events

Syntax 1:

public delegate void NotificationHandler(String notification);
public event NotificationHandler NotificationsEvent;

Standard Syntax:

class EventArgsChild: EventArgs{}
event EventHandler<EventArgsChild> NotificationsEvent;

Standard Event Pattern

EventArgs: Empty class, should be inherited and implemented

EventHandler: Delegate with params object and EventArgs derived child

public delegate void EventHandler(object sender, EventArgs e);
EventArgs.Empty: Sent to EventArgs e instead of null.