C# Delegates

Array Class Collections File Keyword String .NET ASP.NET Cast Compression Data Delegate Directive Enum Exception If Interface LINQ Loop Method Number Process Property Regex Sort StringBuilder Struct Switch Time Windows WPF

Lambda: programming term

In early computers,
methods
and data were separate. Methods acted upon data.
As programming advanced,
methods became data,
so actions too could be objects. The delegate keyword helps us make method objects.

Lambda syntax:

(a, b) => (a != b)

Arguments: two variables (a, b)
Returns:   bool value    (a != b)

Example

This program declares a delegate type D that receives a string, and returns no value. In Main, we create an instance of type D. We specify the method body with a lambda expression.

Keyword: keywords direct program behavior

Then:We call the delegate D method implementation with the argument "cat" using the Invoke method. This is appropriate for the Internet.

Tip:This program uses the "delegate" keyword. But many programs use higher-order procedures with just lambda expressions.

Program that uses delegate: C#

using System;

class Program
{
    delegate void D(string value);

    static void Main()
    {
	// ... Specify delegate with lambda expression.
	D d = v => Console.WriteLine(v);
	// ... Invoke delegate.
	d.Invoke("cat");
    }
}

Output

cat

Lambda

Lambda expression syntax

The syntax for delegate functions can be complex. Lambda expressions provide a simple and terse way of specifying functions. They use the => syntax to separate formal parameters and the method body.

Lambda: SyntaxTip

Tip:Lambda expressions are used throughout C# programs. Common methods receive them as arguments.

Tip 2:Whenever you see a method that receives a Predicate, Action, Func or Comparison, a lambda can be passed.

Example 2

Semicolon

Next, we build upon the delegate concept. We declare a delegate type UppercaseDelegate. It receives a string, and returns a string. We create instances of this delegate Type in the Main method.

Note:We need a delegate declaration to create instances of the delegate type using the new-operator.

Important:When you construct instances of the delegate type, the target method must have the same return value and arguments.

Program 2 that uses delegate type: C#

using System;

class Program
{
    delegate string UppercaseDelegate(string input);

    static string UppercaseFirst(string input)
    {
	char[] buffer = input.ToCharArray();
	buffer[0] = char.ToUpper(buffer[0]);
	return new string(buffer);
    }

    static string UppercaseLast(string input)
    {
	char[] buffer = input.ToCharArray();
	buffer[buffer.Length - 1] = char.ToUpper(buffer[buffer.Length - 1]);
	return new string(buffer);
    }

    static string UppercaseAll(string input)
    {
	return input.ToUpper();
    }

    static void WriteOutput(string input, UppercaseDelegate del)
    {
	Console.WriteLine("Your string before: {0}", input);
	Console.WriteLine("Your string after: {0}", del(input));
    }

    static void Main()
    {
	// Wrap the methods inside delegate instances and pass to the method.
	WriteOutput("perls", new UppercaseDelegate(UppercaseFirst));
	WriteOutput("perls", new UppercaseDelegate(UppercaseLast));
	WriteOutput("perls", new UppercaseDelegate(UppercaseAll));
    }
}

Output

Your string before: perls
Your string after: Perls
Your string before: perls
Your string after: perlS
Your string before: perls
Your string after: PERLS
Method

In this example, WriteOutput is called three times—it receives two arguments each time. The second argument is of type UppercaseDelegate. In Main, the UppercaseDelegate instances are constructed with the delegate constructor.

Note:The target method is specified as the sole argument. It is a method name, not a variable.

Finally:In WriteOutput, the UppercaseDelegate argument is invoked. We use two parentheses after the parameter name.

Anonymous function

Question mark

Anonymous functions include lambda expressions. You can pass a lambda expression as the implementation of the delegate. You can construct the UppercaseDelegate by specifying a lambda expression inside the constructor itself.

Note:This is functionally equivalent to using a static method with the same return value and argument.

Anonymous Functions
Program that uses lambda expression, delegate: C#

using System;

class Program
{
    // ...
    // ... (Paste other methods here)
    // ...

    static void Main()
    {
	WriteOutput("perls", new UppercaseDelegate(x => x.ToUpper()));
    }
}

Output

PERLS

Predicate

True keyword

Next, this example program uses the Predicate generic delegate type with an int type parameter. It uses a lambda expression to specify that the function returns true when the argument is equal to 5.

Then:The Invoke method is used to demonstrate that the Predicate correctly works.

Predicate
Program that uses Predicate: C#

using System;

class Program
{
    static void Main()
    {
	Predicate<int> predicate = value => value == 5;
	Console.WriteLine(predicate.Invoke(4));
	Console.WriteLine(predicate.Invoke(5));
    }
}

Output

False
True

Action

About part

In the .NET Framework, Action instances represent a method that returns void. You can call Invoke on the Action instance and then the method will execute. These are useful in a variety of program contexts.

Action

Func

Func keyword

A Func instance is a delegate to a method that receives arguments and returns a value. It is used in the same general way as Action, but it has a return value. So you can assign variables to its result.

Func

Comparison

Equals sign

The .NET Framework also provides a delegate type that is specifically used to compare objects. This is useful when calling the List.Sort or Array.Sort methods. Comparison is often used in C# programs.

Tip:Using methods such as List.Sort or Array.Sort (with a Comparison) is often faster than using LINQ expressions to sort on a property.

Comparison

Events

Lightning bolt

Events allow you to specify that when external event occurs, such as a mouse click, a delegate method should always be executed. Events are most commonly used in user interfaces such as Windows Forms.

But:You can define custom events in any program. They are occasionally useful in complex programs.

Event

LINQ

Method call

In LINQ extensions, delegate methods are extensively used. Even query expressions (such as select statements) are implemented with methods that receive delegates. Many extension methods require delegate use.

LINQ

Summary

Delegate syntax is at first confusing. Once you understand the instantiation model and type system, it is useful. With the type system, the language offers the ability to specify actions as data.

C#