C# Delegate Method Example
A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.
Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates.
Example Code:
using System;
/*
IDEA Developers
@ideadevelopers
*/
public class SimpleDelegate{
public delegate void IDEADelegate(string text);
public static IDEADelegate mDelegate;
public static void ShowText1(string text){
Console.WriteLine(text + " from Method 1");
}
public static void ShowText2(string text){
Console.WriteLine(text + " from Method 2");
}
public static void ShowText3(string text){
Console.WriteLine(text + " from Method 3");
}
public static void Main(){
if(mDelegate == null){
Console.WriteLine("Delegate Has No Receiver");
}
// adding methods to delegate
mDelegate += ShowText1;
mDelegate += ShowText2;
mDelegate += ShowText3;
if(mDelegate != null){
mDelegate("Hello World");
}
// removing methods from delegate
mDelegate -= ShowText1;
mDelegate -= ShowText2;
mDelegate -= ShowText3;
if(mDelegate == null){
Console.WriteLine("Delegate Has No Receiver");
}
}
}
No comments