Monday 1 February 2016

What is Delegates in C# Example ? Use of Delegates in C#



Basically delegates in c# are type safe objects which are used to hold reference of one or more methods in c#.net. Delegates concept will match with pointer concept of c language. 

Whenever we want to create delegate methods we need to declare with delegate keyword and delegate methods signature should match exactly with the methods which we are going to hold like same return types and same parameters otherwise delegate functionality won’t work if signature not match with methods.

Example:-

using System;

namespace ConsoleDemoApp
{
    public delegate int DelegatSample(int a, int b);
    public class Sampleclass
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
        public int Sub(int a, int b)
        {
            return a -b;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Sampleclass sc = new Sampleclass();

            DelegatSample delgate1 = sc.Add;
            int i = delgate1(100, 200);
            Console.WriteLine(i);
            DelegatSample delgate2 = sc.Sub;
            int j = delgate2(200, 100);
            Console.WriteLine(j);
            Console.ReadKey();
        }
    }

}



Output:-



















What is the use of Delegates?

Suppose if you have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates.

Delegates are two types

      -  Single Cast Delegates
      -  Multi Cast Delegates

Single Cast Delegates

Single cast delegate means which hold address of single method like as explained in above example.

Multicast Delegates

Multi cast delegate is used to hold address of multiple methods in single delegate. To hold multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -=

Multicast delegates will work only for the methods which have return type only void. If we want to create a multicast delegate with return type we will get the return type of last method in the invocation list




Check below sample code for multicast delegate declaration and methods declaration


public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}


Output:-





No comments:

Post a Comment