What is a delegate?
A delegate is a type safe function pointer. That is, it holds a reference (pointer) to a function.
The signature of the delegate must match the signature of the function,the delegate points to, otherwise you get a complier error. This is the reason delegates are called as type safe function pointers.
A Delegate is similar to a class. You can create an instance of it, and when you do so, you pass in the funstion name as a parameter to the delegate constructor, and it is to this function the delegate will point to.
Tip to remember delegate syntax: Delegates syntax look very much similar to a method with a delegate keyword.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;
namespace ConsoleApplication4
{
class Program
{
public delegate void HelloFunctionDelegate(string Message);
public static void Main()
{
HelloFunctionDelegate del = new HelloFunctionDelegate(Hello);
del("This is the delegate function");
// A delegate is a type safe function pointer
}
public static void Hello(string strMessage)
{
Console.WriteLine(strMessage);
Console.ReadLine();
}
}
}
=======================================================================
DEMO DEMO ON DELEGATE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;
namespace ConsoleApplication4
{
class Program
{
public static void Main()
{
List<Employee> empList = new List<Employee>();
empList.Add(new Employee() { ID = 101, Name = "Malla", Salary = 5000, Experience = 5 });
empList.Add(new Employee() { ID = 102, Name = "Reddy", Salary = 4000, Experience = 4 });
empList.Add(new Employee() { ID = 103, Name = "Mathew", Salary = 3000, Experience = 3 });
empList.Add(new Employee() { ID = 104, Name = "Sam", Salary = 6000, Experience = 7 });
Employee.PromoteEmployee(empList);
Console.ReadLine();
}
}
class Employee
{
public int ID{get;set;}
public string Name { get; set; }
public int Salary { get; set; }
public int Experience { get; set; }
public static void PromoteEmployee(List<Employee> employeeList)
{
foreach (Employee employee in employeeList)
{
if (employee.Experience >= 5)
{
Console.WriteLine(employee.Name + " Promoted");
Console.ReadLine();
}
}
}
}
}
=======================================================================
USING DELEGATE THE ABOVE EXAMPLE IS MODIFIED
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;
namespace ConsoleApplication4
{
class Program
{
public static void Main()
{
List<Employee> empList = new List<Employee>();
empList.Add(new Employee() { ID = 101, Name = "Malla", Salary = 5000, Experience = 5 });
empList.Add(new Employee() { ID = 102, Name = "Reddy", Salary = 4000, Experience = 4 });
empList.Add(new Employee() { ID = 103, Name = "Mathew", Salary = 3000, Experience = 3 });
empList.Add(new Employee() { ID = 104, Name = "Sam", Salary = 6000, Experience = 7 });
//IsPromotable ispromotable = new IsPromotable(Promote);
//Employee.PromoteEmployee(empList, ispromotable);
// Lamda expressions
Employee.PromoteEmployee(empList,emp =>emp.Experience >=5);
Console.ReadLine();
}
//******** below commented section is to write shortcut code using lamda expression.*****//
//public static bool Promote(Employee emp)
//{
// if (emp.Experience >= 5)
// {
// return true;
// }
// else
// {
// return false;
// }
//}
}
delegate bool IsPromotable(Employee empl);
class Employee
{
public int ID{get;set;}
public string Name { get; set; }
public int Salary { get; set; }
public int Experience { get; set; }
public static void PromoteEmployee(List<Employee> employeeList,IsPromotable isEligibleToPromote)
{
foreach (Employee employee in employeeList)
{
if (isEligibleToPromote(employee))
{
Console.WriteLine(employee.Name + " Promoted");
Console.ReadLine();
}
}
}
}
}
===================================================================
MULTICAST DELEGATES
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;
namespace ConsoleApplication4
{
public delegate void SampleDelegate();
class Program
{
public static void Main()
{
//SampleDelegate del1, del2, del3, del4;
//del1 = new SampleDelegate(SampleMethodOne);
//del2 = new SampleDelegate(SampleMethodTwo);
//del3 = new SampleDelegate(SampleMethodThree);
//del4 = del1 + del2 + del3;
//del4();
//Console.ReadLine();
SampleDelegate del = new SampleDelegate(SampleMethodOne);
del += SampleMethodTwo;
del += SampleMethodThree;
del();
Console.ReadLine();
}
public static void SampleMethodOne()
{
Console.WriteLine("Samplemethodone Invoked");
Console.ReadLine();
}
public static void SampleMethodTwo()
{
Console.WriteLine("SamplemethodTwo Invoked");
Console.ReadLine();
}
public static void SampleMethodThree()
{
Console.WriteLine("SamplemethodThree Invoked");
Console.ReadLine();
}
}
}
=====================================================================
Multicast delegates
A multicast delegate is a delegate that has references to more than one function.when you invoke a multicast delegate, all the functions the delegate is pointing to, are invoked.
There are 2 approaches to create a multicast delegate . depending on the approach you use
+ or += to register a method with the delegate
- or -= to un-register a method with the delegate.
Note: A multicast delegate, invokes the methods in the invocation list, in the same order in which they are added.
If the delegate has a return type other than void and if the delegate is a multicast delegate,
only the value of the last invoked method will be returned. Along the same lines, if the delegate has an out paraameters, the value of the output parameters, will be the value assigned by the last method.
Common interview question- where do you use multicast delegates?
Multicast delegate makes implementation of observer design patterns very simple. Observer pattern is also called as publish/subscribe pattern.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;
namespace ConsoleApplication4
{
public delegate int SampleDelegate();
class Program
{
public static void Main()
{
//SampleDelegate del1, del2, del3, del4;
//del1 = new SampleDelegate(SampleMethodOne);
//del2 = new SampleDelegate(SampleMethodTwo);
//del3 = new SampleDelegate(SampleMethodThree);
//del4 = del1 + del2 + del3;
//del4();
//Console.ReadLine();
SampleDelegate del = new SampleDelegate(SampleMethodOne);
del += SampleMethodTwo;
int DelegateReturnedValue = del();
Console.WriteLine("DelegateReturnedValue= {0}", DelegateReturnedValue);
Console.ReadLine();
}
public static int SampleMethodOne()
{
return 1;
Console.ReadLine();
}
public static int SampleMethodTwo()
{
return 2;
Console.ReadLine();
}
}
}
No comments:
Post a Comment
Note: only a member of this blog may post a comment.