Monday, 10 July 2017

when & why to use delegates?

A delegate is a reference to a method. Whereas objects can easily be sent as parameters into methods, constructor or whatever, methods are a bit more tricky. But every once in a while you might feel the need to send a method as a parameter to another method, and that's when you'll need delegates.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace DelegatesApp
{
    class Person
    {
        public delegate String GetMsg(int a);
        public String name;
        public int age;

        public String GetChildMessage(int age) {

            return (age<=15 && age>0)? age.ToString() + " : age is child age Person":"";
        }

        public String GetAdultMessage(int age)
        {
            return (age>15&& age<=60)? age.ToString() + " : age is Adult age Person" :"";
        }

        public String GetOldMessage(int age)
        {
            return age>60? age.ToString() + " : age is Old age Person":"";
        }

        public List<Person> GetLstPerson()
        {
            Person p1 = new Person() { name = "John", age = 41 };
            Person p2 = new Person() { name = "Jane", age = 69 };
            Person p3 = new Person() { name = "Jake", age = 12 };
            Person p4 = new Person() { name = "Jessie", age = 25 };
            List<Person> lst = new List<Person> { p1,p2,p3,p4};

            return lst;
        }

        public void DisplayMsg(List<Person> person, GetMsg getmsg)
        { 
        foreach(Person p in  person)
        {
            if(getmsg(p.age)!="")
            Console.WriteLine(getmsg(p.age));
        }
        }



    }
}


 class Program
    {
       
        static void Main(string[] args)
        {
         
            Person p = new Person();
            p.DisplayMsg(p.GetLstPerson(), p.GetChildMessage);
            p.DisplayMsg(p.GetLstPerson(), p.GetAdultMessage);
            p.DisplayMsg(p.GetLstPerson(), p.GetOldMessage);
            Console.ReadLine();

        }


No comments:

Post a Comment