ASP.NET

Delegates

The C and C++ languages have long used the concept of function pointer. This was even more useful when programming for the Microsoft Windows operating…

8 min read1,866 words12 code samples

Fundamentals of Delegates#

Introduction#

The C and C++ languages have long used the concept of function pointer. This was even more useful when programming for the Microsoft Windows operating systems because the Win32 library relies on the concept of callback functions. Callback functions are used in Microsoft Windows programming to process messages. For this reason and because of their functionality, callback functions were carried out in the .NET Framework but they were defined with the name of delegate. A delegate is a special type of user-defined variable that is declared globally, like a class. A delegate provides a template for a method, like an interface provides a template for a class. Like an interface, a delegate is not defined. Its role is to show what a useful method would look like. To support this concept, a delegate can provide all the necessary information that would be used on a method. This includes a return type, no argument or one or more arguments.

Creating a Delegate#

To create a delegate, you use the delegate keyword. The basic formula used to create a delegate is:

C#
[attributes] [modifiers] delegate ReturnType Name ([formal-parameters]);

The attributes factor can be a normal C# attribute. The modifier can be one or an appropriate combination of the following keywords: new, public, private, protected, or internal. The delegate keyword is required. The ReturnType can be any of the data types we have used so far. It can also be a type void or the name of a class. The Name must be a valid C# name. Because a delegate is some type of a template for a method, you must use parentheses, required for every method. If this method will not take any argument, leave the parentheses empty. Here is an example:

C#
public delegate void Simple();

public class Exercise
{

}

After declaring a delegate, it only provides a template for a method, not an actual method. In order to use it, you must define a method that would carry an assignment to perform. That method must have the same return type and the same (number of) argument(s), if any. For example, the above declared delegate is of type void and it does not take any argument. you can define a corresponding method as follows:

C#
public delegate void Simple();

public class Exercise
{
    public void Welcome()
    {

    }
}

With such a method implemented, you can associate it to the name of the delegate. To do that, where you want to use the method, declare a variable of the type of the delegate and assign the method to the delegate variable. Because you are assigning the method to a delegate, one of the rules of delegates is that you must not apply the parentheses to the method.

Accessing a Delegate#

Introduction#

Once you have assigned a method to a delegate variable, you can use the delegate variable as if it were a defined method. That is, you can call as you would a normal method.

An Anonymous Delegate#

We created a method that would be associated with a delegate. You can create a delegate, then, when you need to use, create a type of local implementation of a method and use it. In other words, you do not have to explicitly define a method prior to using the delegate. Such a method is referred to as anonymous. Before implementing an anonymous method, first declare the delegate you will use. To create an anonymous method, declare a variable for the delegate and assign it the delegate keyword as if it were a method. That is, followed by parentheses and curly brackets that would represent the body of the method. In the body of the anonymous method, do whatever you want. Once you have done this, you can then call the delegate variable as if it were a normal method.

The Lambda Operator#

You may also create an anonymous method using an operator called lambda and represented by =>. To use the lambda operator to create an anonymous method, omit the delegate keyword and follow the parentheses by the operator. Once you have done this, you can call the delegate variable as a method.

A Delegate that Returns a Value#

You may create a delegate that returns a value. When creating the delegate, specify the data type to the left side of the name of the delegate. When defining a method that would be associated with the delegate, remember that the method must return the same type of value. In the body of the method, use it as you see fit. Before exiting the method, make sure you appropriately return a value. To use the method, follow the same approach as above. This time, when calling the delegate variable, you should use the parentheses. In the same way, you can create an anonymous method that implements the delegate. To do this, follow the same rule we defined earlier. For example, you can use the delegate keyword.

Delegates Compositions#

One of the characteristics that set delegates apart from C/C++ function pointers is that one delegate can be added to another using the + operation. This is referred to as composition. This is done by adding one delegate variable to another as in a = b + c.

Delegates and Arguments#

Introduction#

If you want to use a method that takes arguments and associate it to a delegate, when declaring the delegate, provide the necessary argument(s) in its parentheses. Here is an example of a delegate that takes two arguments (and returns a value):

C#
delegate double Doubler(double x);

When defining the associated method, besides returning the same type of value if not void, make sure that the method takes the same number of arguments.

Using an Argumentative Delegate#

To associate the method to the delegate, you can declare a variable for the delegate and assign the name of the method to it. Notice that only the name of the method is passed to the delegate. To actually use the delegate, when calling it, add the parentheses to it and in the parentheses, provide a value for the argument(s).

A Lambda Expression#

You can create an anonymous method for a delegate that takes one or more arguments. You can do this with the delegate keyword. In its parentheses, pass an argument that is the same type as the argument of the delegate. Then, in the body of the method, do what you judge necessary. When calling the variable of the delegate, use the same rules we have applied so far. This technique of using the delegate keyword was introduced in C# 2.0 and has been updated with the lambda operator. Therefore, this was probably the last time we use it since we have been able to apply to varied types of delegates. Instead of the delegate keyword, you can define an anonymous method using the lambda operator. In this case, in the parentheses of the lambda expression, enter the data type of the argument followed by its name. In the body of the anonymous method, use the argument as you see fit. After defining the method, you can call it like a normal method.

A Delegate With Many Arguments#

A delegate can take more than one argument. To start, when declaring it, pass the desired number of arguments. If you will use a method to associate to the delegate, then create the method also. Here is an example:

C#
delegate double Addition(double x, double y);

public class Algebra
{
    public static double Plus(double a, double b)
    {
        return a + b;
    }
}

To use the delegate, follow the techniques we have applied so far and call the delegate as a method. If you want to use a lambda expression to create an anonymous method, in its parentheses, pass the right number of arguments. In the body of the anonymous method, use the arguments ad you see fit. To use the delegate, call it as you would a normal method.

A Delegate Passed as Argument#

Using delegates, one method can be indirectly passed as argument to another method. To proceed, first declare the necessary delegate. Here is a example of such a delegate:

C#
public delegate double Squared(double x);

A delegate can be passed as argument to a method. Such an argument would be used as if it were a method itself. This means that, when accessed in the body of the method, the name of the delegate must be accompanied by parentheses and if the delegate takes an argument or arguments, the argument(s) must be provided in the parentheses of the called delegate. After declaring a delegate, remember to define a method that implements the needed behavior of that delegate. You can define the associated method in a class other than the one where the delegate would be used. You can also define the method in the class where the delegate would be needed. Once the method that implements the delegate is known, you can use the delegate as you see fit. To do that, you can declare a variable of the type of that delegate and assign it to the variable.

Delegates and Classes#

Introduction#

So far, we have learned how to create and use delegate of primitive types. We learned how to create a void delegate, how to create a delegate that returns a value, and how to create a delegate that takes one or more argument. Just as a reminder, here is an example:

C#
delegate double Multiplication();

public class Cube
{
    private double Side;

    public Cube()
    {
        Side = 0;
    }

    public Cube(double s)
    {
        Side = s;
    }

    internal double Area()
    {
        return 6 * Side * Side;
    }

    internal double Volume()
    {
        return Side * Side * Side;
    }
}

public class Exercise
{
    public void Use()
    {
        Cube SmallBox = new Cube(25.58);

        Multiplication AreaDefinition = SmallBox.Area;
        Multiplication VolDefinition = SmallBox.Volume;
    }
}

A Delegate that Returns an Object#

A delegate can be created to return a value that is of a class type. Of course you must know the class you want to use because the compiler would like to know the type of value that the delegate would return. You can use one of the many built-in classes or you can create your own class. When creating the delegate, specify the name of the class to its left as the returned type of value. Here is an example:

C#
delegate Person Creator();

public class Person
{
    public string FirstName;
    public string LastName;
}

After doing this, you can create a method that implements the delegate. The method must return the same type of value as the delegate. Here is an example:

C#
delegate Person Creator();

public class Person
{
    public string FirstName;
    public string LastName;
}

public class Exercise
{
    private static Person Create()
    {
        Person pers = new Person();
        pers.FirstName = "Julius";
        pers.LastName = "Krands";
        return pers;
    }
}

To use the delegate, declare a variable for it and assign the method to it. Here is an example:

C#
delegate Person Creator();

public class Person
{
    public string FirstName;
    public string LastName;
}

public class Exercise
{
    private Person Create()
    {
        Person pers = new Person();
        pers.FirstName = "Julius";
        pers.LastName = "Krands";
        return pers;
    }

    static void Use()
    {
        Creator crt = Create;
    }
}

You can then call use the variable as you see fit. Instead of explicitly creating a method that implements the delegate, you can create an anonymous method using a lambda expression. In the body of the anonymous method, make sure you return a value of the type of the delegate. Here is an example:

C#
delegate Person Creator();

public class Person
{
    public string FirstName;
    public string LastName;
}

public class Exercise
{
    private void Use()
    {
        Creator Create = () =>
        {
            var PersonalInformation = new Person();

            PersonalInformation.FirstName = "Julius";
            PersonalInformation.LastName = "Krands";

            return PersonalInformation;
        };
       
        Create();
    }
}

A Delegate that Takes an Object as Argument#

A delegate can be created to receive a class type as argument. When creating the delegate, in its parentheses, specify the class whose value it takes as argument. Here is an example:

C#
delegate void Anchor(Person p);

public class Person
{
    public string FirstName;
    public string LastName;
}

To use the delegate, you can first create a method that implements the delegate, then declare a variable for the delegate and assign the method to it. If you prefer to create an anonymous method using a lambda expression, in the parentheses, enter a name for the argument and use that argument in the body of the method as you see fit. You can then call the method as you see fit. In the same way:

  • You can create a delegate that takes a class as argument and returns a class type
  • You can create a delegate that takes more than one argument. One of the arguments could be a class type and the other(s) a class or a primitive type

Previous Copyright © 2009 C# Key Next