Information Technology Reference
In-Depth Information
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:
Delegate type Variable
MyDel delVar;
You can create a delegate object by using the new operator, as shown in the following code.
The operand of the new operator consists of the following:
￿
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.
Instance method
delVar = new MyDel( MyInstObj.MyM1 ); // Create delegate and save ref.
dVar = new MyDel( SClass.OtherM2 ); // Create delegate and save ref.
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 equivalent. Using the shortcut syn-
tax works, because there is an implicit conversion between a method name and a compatible
delegate type.
delVar = MyInstObj.MyM1; // Create delegate and save reference.
dVar = SClass.OtherM2; // Create delegate and save reference.
For example, the following code creates two delegate objects—one with an instance
method, and the other with a static method. Figure 15-3 shows the instantiations of the dele-
gates. This code assumes that there is a class object called MyInstObj , which has a method
called MyM1 that 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 .
Search WWH ::




Custom Search