ডেলিগেট হলো একটি টাইপ-সেফ ফাংশন পয়েন্টার। এটি মেথডের রেফারেন্স ধারণ করে এবং রানটাইমে পরিবর্তন করা যায়। ইভেন্ট এবং কলব্যাকের জন্য ব্যবহৃত হয়। সব ডেলিগেট System.Delegate থেকে ইনহেরিট করে।
সিনট্যাক্স
delegate
উদাহরণ: কনসোল এবং ফাইলে লেখা
using System;
using System.IO;
namespace DelegateAppl
{
class PrintString
{
static FileStream fs;
static StreamWriter sw;
public delegate void PrintStringDelegate(string s);
public static void WriteToScreen(string str)
{
Console.WriteLine("The String is: {0}", str);
}
public static void WriteToFile(string s)
{
fs = new FileStream("c:\\message.txt", FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
sw.WriteLine(s);
sw.Flush(); sw.Close(); fs.Close();
}
public static void SendString(PrintStringDelegate ps)
{
ps("Hello World");
}
static void Main(string[] args)
{
PrintStringDelegate ps1 = new PrintStringDelegate(WriteToScreen);
PrintStringDelegate ps2 = new PrintStringDelegate(WriteToFile);
SendString(ps1);
SendString(ps2);
Console.ReadKey();
}
}
}
আউটপুট
The String is: Hello World
ডেলিগেট মাল্টিকাস্ট হতে পারে (+= দিয়ে একসাথে একাধিক মেথড কল)।