Wednesday, 4 December 2013

when & why to use delegates?



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegateApp
{
    /// <summary>
    /// A class to define a person
    /// </summary>
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
    }

    class Program
    {
        //Our delegate
        public delegate bool FilterDelegate(Person p);

        static void Main(string[] args)
        {

            //Create 4 Person objects
            Person p1 = new Person() { Name = "John", Age = 41 ,Address ="Hyd"};
            Person p2 = new Person() { Name = "Jane", Age = 69 ,Address = "Blr"};
            Person p3 = new Person() { Name = "Jake", Age = 12 , Address ="NLR" };
            Person p4 = new Person() { Name = "Jessie", Age = 25,Address ="Chennai" };

            //Create a list of Person objects and fill it
            List<Person> people = new List<Person>() { p1, p2, p3, p4 };
            DisplayPeople("Children:", people, IsChild);
            DisplayPeople("Adults:", people, IsAdult);
            DisplayPeople("Seniors:", people, IsSenior);
            DisplayPeople("Middle Age:", people, MiddleAge);

            List<Person> test = new List<Person>() { p1 };
            TestDisplay("testing data", test);
            Console.Read();
        }

        /// <summary>
        /// A method to filter out the people you need
        /// </summary>
        /// <param name="people">A list of people</param>
        /// <param name="filter">A filter</param>
        /// <returns>A filtered list</returns>
        ///
        static void TestDisplay(string title1, List<Person> test)
        {
            Console.WriteLine(title1);
            foreach (Person t in test)
            {
                Console.WriteLine(" {0} ,{1} years of testing data", t.Name, t.Age);
            }
        }
       
        static void DisplayPeople(string title, List<Person> people, FilterDelegate filter)
        {
            Console.WriteLine(title);

            foreach (Person p in people)
            {
                if (filter(p))
                {
                    Console.WriteLine("{0}, {1} years old", p.Name, p.Age ,p.Address );
                }
            }

            Console.Write("\n\n");
        }

        //==========FILTERS===================
        static bool IsChild(Person p)
        {
            return p.Age <= 18;
        }

        static bool IsAdult(Person p)
        {
            return p.Age >= 18;
        }

        static bool IsSenior(Person p)
        {
            return p.Age >= 65;
        }
        static bool MiddleAge(Person p)
        {
            return p.Age >= 18 && p.Age <= 40;
        }
    }
}
















.
.
.
.
.
.

Delegates Overview
Delegates have the following properties:
  • Delegates are similar to C++ function pointers, but are type safe.
  • Delegates allow methods to be passed as parameters.
  • Delegates can be used to define callback methods.
  • Delegates can be chained together; for example, multiple methods can be
    called on a single event.
  • Methods don't need to match the delegate signature exactly. For more
    information, see Covariance and
    Contra variance
  • C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately
    defined method.