Generic delegates — RexDac Academy

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

Level 6 — Generics and Delegates

Generic delegates

Original notes by SunDiaL · View English source

Of course, declaring delegate types again and again by hand is tedious, and actually unnecessary, because what you actually need to do given all those tools until now, is to create one good generic delegate type. And that's precisely what the .Net framework provides now out of the box.

Action

Action is a generic delegate type representing a function returning void. It supports up to ~8 parameters, specified with <> syntax.

public void Main()
{
	Action<string> log = Console.WriteLine;
	log("Hello world");
}

Function<>

Func is the same as Action, except it returns a value. It also supports up to ~8 parameters, +1 more for the output.

public void Main()
{
	Func<int, string> conv = Convert.ToString;
	string result = conv(5); //"5"
}

Predicate<>

Shorthand for a Func<> that returns bool. Basically a condition.

public bool IsPositive(int x)
{
	return x>=0;
}

public void Main()
{
	Preticate<int> condition = IsPositive;
	condition(5); //true
}