Delegates — RexDac Academy

RexDac AcademyTechnical notes · Some prior knowledge helps
0%Published notes read · this device

Level 6 — Generics and Delegates

Delegates

Original notes by SunDiaL · View English source

I briefly mentioned in Operands how operations themselves can become operands. Delegates are the feature that allows us to accomplish just that. They allow you to treat functions as values — to assign them to variables, pass them around, and invoke them later. I say "delegates", but there's two things here really.

Delegate type

The delegate type, if it wasn't obvious enough from the name, is the type. Similar to classes, you first have to communicate to your computer that this type exists and describe what it looks like. This is a declarative statement, and the syntax for it is ReturnType + DelegateName + Parameters. The signature, if you will, but it's not quite the same signature.

public delegate void Writer(string message);

Note: delegates have the same access modifiers classes do.

Delegate

The delegate is the variable. The only difference from other variables is that it holds functions that match what the delegate type specifies.

A delegate can hold more than one function.

public void Main()
{
	Writer log = Console.WriteLine; //Notice the absence of "()". myDelegateName is not 
											   //assigned the result of WriteLine, it is assigned the 
											   //function itself.

	log += File.WriteLine; //Notice the "+=". Multiple functions can be added
									  // (or removed with -=) to the same delegate.

	log("Hello world"); //actual function call. This calls both Console.WriteLine() 
								   //and File.WriteLine()
}

Note: A delegate can be overwritten, which brings us to the next topic:

Events