How to instantiate and invoke static and instance method using delegates ?

Refer below code to understand :
using System;

delegate void DelMethod(int x); // This is the delegate declaration
// Example is Class containing static method and instance method to be instantiated
class Example
{
public static void StaticMethod(int i) {
Console.WriteLine("M1: " + i);
}
public void InstanceMethod(int i) {
Console.WriteLine("M3: " + i);
}
}
// Below class contains code to instantiate and invoke static and instance method using delegates
class Test
{
static void Main() {
DelMethod cd1 = new DelMethod (Example.StaticMethod); // Instantiate Static Method delegate
cd1(-1); // Invoke Static Method

Example c = new Example ();
DelMethod cd2 = new DelMethod (c.InstanceMethod); // Instantiate InstanceMethod delegate

cd2(5); // Invoke Instance Method
}
}

No comments:

Popular Posts