We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Friday, May 29, 2015

Delegates

What are Delegates in C# and Explain with Example?
 A delegate is a type that represents references to methods with a particular parameter list and return type. A delegate (known as function pointer in C/C++) is a reference type that invokes single/multiple methods (s) through the delegate instance. It holds a reference to the methods. Whenever we want to create a delegate methods we need to declare with delegate keyword.

What is the use of Delegates?
Suppose if we have multiple methods with the same signature (return type & number of parameters) and want to call all the methods with a 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 the address of a single method like as explained in the example below.
Ex:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace SingleDelegate
{
 public delegate int SingleDelegate(int x, int y);

public class DeligateClass
{
 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)
{
 DeligateClass cs = new DeligateClass();

SingleDelegate sd = cs.Add;

int i = sd(8, 6);

Console.WriteLine("Add Result:{0}", i);

SingleDelegate sd1 = cs.Sub;

int j=sd1(8,6);

Console.WriteLine("Sub Result:{0}", j);

Console.ReadLine();
}

}

}
 Multicast Delegates
A multicast delegate is used to hold the address of multiple methods in the single delegate. To hold multiple addresses with delegate we will use overloaded += operator and if we want to 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 the last method in the invocation list

Ex:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace multicastDeligate
{
 public delegate void Mulitcastdeligate(int x,int y);

public class Delegateclass
{
 public static void Add(int a, int b)

{ Console.WriteLine(a + b);

}
public static void Sub(int a, int b)

{
Console.WriteLine(a - b);

}
public static void Mul(int a, int b)

{
Console.WriteLine(a * b);

}public static void div(int a, int b)

{
Console.WriteLine(a / b);

}

}
class Program

{
static void Main(string[] args)

{
Delegateclass dc = new Delegateclass();

Mulitcastdeligate md = Delegateclass.Add;

md += Delegateclass.Sub;

md += Delegateclass.Mul;

md += Delegateclass.div;

md(8, 4);
Console.ReadLine();

}

}

}
 
 
 

No comments: