A Simple Delegate Example

Akiii
Posted by Akiii under C# category on | Points: 40 | Views : 1123
Hi,
A delegate is similar to what we know as a function pointer in C or C++. It encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to a code which can call the referenced method, without having to know at compile time which method will be invoked. Delegates are object-oriented, type-safe, and secure. For example, suppose you have two methods :-

public static void Method1(string msg)
{
Console.WriteLine("Method1 : " + msg);
}

public static void Method2(string msg)
{
Console.WriteLine("Method2 : " + msg);
Console.ReadLine();
}


Now you declare a delegate like this :-
public delegate void TestDelegate(string msg);


Now, how do you call the above two methods by using delegate ? Follow the example then :-


static void Main(string[] args)
{
TestDelegate td = new TestDelegate(Method1);
td("hello");
td = new TestDelegate(Method2);
td("hello");
}


Here, you made a delegate object known as "td". In that you passed method1. Now, the delegate object is referring to the method1, in other words, "td" has a reference of method1. You simple invoke the method by passing the parameter. The same is true with the second method.

Try running the code and you will see the output..

Remember, the signature of the delegate should match the method you are calling otherwise it will give a compile-time error.



Thanks and Regards
Akiii

Comments or Responses

Login to post response