Skip to content

Creating the Delegate Object

A delegate is a reference type and therefore has both a reference and an object. After a delegate type is declared, you can declare variables and create objects of the type. The following code shows the declaration of a variable of a delegate type:

There are two ways you can create a delegate object. The first is to use an object-creation expression
with the new operator, as shown in the following code. The operand of the new operator consists of the

  • The delegate type name.
  • A set of parentheses containing the name of a method to use as the first member in
    the invocation list. The method can be either an instance method or a static method.

You can also use the shortcut syntax, which consists of just the method specifier, as shown in the following code. This code and the preceding code are semantically equivalent. Using the shortcut syntax works because there is an implicit conversion between a method name and a compatible delegate type.

For example, the following code creates two delegate objects: one with an instance method and the other with a static method. Below figure shows the instantiations of the delegates. This code assumes that there is an object called myInstObj, which is an instance of a class that has defined a method called MyM1, which returns no value and takes an int as a parameter. It also assumes that there is a class called SClass, which has a static method OtherM2 with a return type and signature matching those of delegate MyDel.

Besides allocating the memory for the delegate, creating a delegate object also places the first method in the delegate’s invocation list. You can also create the variable and instantiate the object in the same statement, using the initializer syntax. For example, the following statements also produce the same configuration shown in above figure.

The following statements use the shortcut syntax but again produce the results shown in above figure

Leave a Reply

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