Monday, August 25, 2014

Delegates in C#

We have used pointers in C, delegates are something like pointers in C but type safe. Previously we send data as parameter but today we send methods as parameter through objects. In C# 2.0 delegates are introduced. It used to send methods to pass through its object. Its like a reference variable to the reference of the method which you have to execute.It is derived  from System.Delegate class and generally use for implementing events and call back method. In the next few lines I will show you how to declare a delegate and how to execute through the object of the delegate.

First we lets see how to declare the delegate in C#.

public delegate int delegate1 (string input);
public delegate void delegate2 (string input);
public delegate string delegate3 (string input);

In these above code two delegates are declared. First one for a method which takes an input string and return a integer value. Second one is taking an input string as first one but returning nothing(void). And third and the last one denotes a method which takes string also return string. So is clear how to declare different delegate. Now lets check how to call the delegates. To call using these delegates we need to create objects of these three delegates. Lets create three objects of these three.

public delegate int delegate1 (string input);
public delegate void delegate2 (string input);
public delegate string delegate3 (string input);

delegate1 obj1 = new delegate1(methodReturnInt);
delegate2 obj2 = new delegate2(methodReturnVoid);
delegate3 obj3 = new delegate3(methodReturnString);

So objects are created of these different delegates.methodReturnInt, methodReturnVoid, methodReturnString  these are the method name which are called by the three delegate objects. Suppose the three methods are like...
 
// return int 
public static int methodReturnInt(sting ip)
{
   return 0;
}

// return void
public static void methodReturnVoid(sting ip)
{
   return ;
}

// return string
public static string methodReturnString(sting ip)
{
   return "Hi !";
}

Now how to call through the objects. Lets see.
static void Main(string[] args)
{
  // creating objects
  delegate1 obj1 = new delegate1(methodReturnInt);
  delegate2 obj2 = new delegate2(methodReturnVoid);
  delegate3 obj3 = new delegate3(methodReturnString);

  // calling methods with value
  obj1("abc");
  obj1("pqr");
  obj1("xyz");
}

I thing now its clear to you how to use delegates in your project after these short session of coding. Try it yourself and bang it. Happy coding.... :)

1 comments:

Post a Comment

Follow by Email

Popular Posts

Pageviews