Initiating delegates using NamedMethod

Let's look at an example of NamedMethod so that we can understand how to initiate a delegate. This is the method that was used prior to C# 2.0:

delegate void MathDelegate(int i, double j);
public class Chapter5Samples
{
// Declare a delegate
public void NamedMethod()
{
Chapter5Samples m = new Chapter5Samples();
// Delegate instantiation using "Multiply"
MathDelegate d = m.Multiply;
// Invoke the delegate object.
Console.WriteLine("Invoking the delegate using 'Multiply':");
for (int i = 1; i <= 5; i++)
{
d(i, 5);
}
Console.WriteLine("");

}
// Declare the associated method.
void Multiply(int m, double n)
{
System.Console.Write(m * n + " ");
}
}
//Output:
Invoking the delegate using 'Multiply':
5 10 15 20 25

In the preceding code, first, we defined a delegate called MathDelegate, which accepts 2 parameters, 1 integer and another double type. Then, we defined a class where we wanted to invoke MathDelegate using a named method known as Multiply.

The MathDelegate d = m.Multiply; line is where we assigned a named method to a delegate.

Named method delegates can encapsulate a static or instance method with any accessible class or structure that matches the type of delegate. This allows the developer to extend these methods.

In the following example, we will see how a delegate can be mapped to static and instance methods. Add the following method to the Chapter5Samples class we created previously:

public void InvokeDelegate()
{
HelperClass helper = new HelperClass();

// Instance method mapped to delegate:
SampleDelegate d = helper.InstanceMethod;
d();

// Map to the static method:
d = HelperClass.StaticMethod;
d();
}

//Create a new Helper class to hold two methods
// Delegate declaration
delegate void SampleDelegate();

internal class HelperClass
{
public void InstanceMethod()
{
System.Console.WriteLine("Instance Method Invoked.");
}

static public void StaticMethod()
{
System.Console.WriteLine("Invoked function Static Method.");
}
}

//Output:
Invoked function Instance Method.
Invoked function Static Method.

In the preceding code, we defined two methods: the first one is a normal method, while the second one is a static method. In the case of invoking delegates using a named method, we can either use the first normal method or the second static method:

  • SampleDelegate d = helper.InstanceMethod;: This is a normal method.
  • d = HelperClass.StaticMethod;: This is a static method.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.67.22