एक प्रतिनिधि को तत्काल करने के लिए नए कीवर्ड का प्रयोग करें। एक प्रतिनिधि बनाते समय, नई अभिव्यक्ति को दिया गया तर्क एक विधि कॉल के समान लिखा जाता है, लेकिन विधि के तर्कों के बिना।
उदाहरण के लिए -
public delegate void printString(string s); printString ps1 = new printString(WriteToScreen);
आप एक अनाम विधि का उपयोग करके एक प्रतिनिधि को तुरंत चालू भी कर सकते हैं -
//declare
delegate void Del(string str);
Del d = delegate(string name) {
Console.WriteLine("Notification received for: {0}", name);
}; आइए एक उदाहरण देखें जो एक प्रतिनिधि को घोषित और तत्काल करता है -
उदाहरण
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl {
class TestDelegate {
static int num = 10;
public static int AddNum(int p) {
num += p;
return num;
}
public static int MultNum(int q) {
num *= q;
return num;
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
} आउटपुट
Value of Num: 35 Value of Num: 175