Short Summary of Delegation in C#

No Comments

Classic

public delegate decimal MathOp(decimal left, decimal right)

public static decimal Add(decimal left, decimal right)
{
	return left + right;
}
private static MathOp GetOp(char op)
{
	switch (op)
	{
		case '+': return Add;
	}
}

Interfaces

public interface IMathOp
{
	decimal Compute(decimal left, decimal right);
}

public class AddOp : IMathOp
{

	decimal Compute(decimal l, decimal r)
	{
		return l + r;
	}
}

private static MathOp GetOp(char op)
{
	switch (op)
	{
		case '+': return new AddOp();
	}
}

Anonymous Methods

public delegate decimal MathOp(decimal left, decimal right)

private static MathOp GetOp(char op)
{
	switch (op)
	{
		case '+': return delegate (decimal l, decimal r) { return l + r};
	}
}

Generic Delegates and Lambda Expressions

public static Func<decimal, decimal, decimal> GetOp(char op)
{
	switch (op)
	{
		case '+': return (l, r) => l + r;
	}
}

For complete details, see Dave Fancher PluralSight course Functional Programming with C#

Categories: C#

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Loading Facebook Comments ...