Saturday, February 7, 2015

Delegate in C#


  1. delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.

Program.cs

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

namespace DelegateExample
{
    class Program
    {
        static void Main(string[] args)
        {
            PropertyClass objPropertyClass = new PropertyClass("prabakaran");

            objPropertyClass.Changed += DelegateAction;
            objPropertyClass.Changed += DelegateAction;
            objPropertyClass.Changed += DelegateAction;
            objPropertyClass.Name = "pk";


            Console.WriteLine(objPropertyClass.Name);
            Console.ReadLine();
        }

        private static void DelegateAction(object sender, EventArgsClass args)
        {
            Console.WriteLine("oldvalue:" + args.OldValue);
            Console.WriteLine("newvalue:" + args.NewValue);
        }

        //private static void DelegateAction(string oldValue, string newValue)
        //{
        //    Console.WriteLine("oldvalue:" + oldValue);
        //    Console.WriteLine("newvalue:" + newValue);
        //}
    }
}

PropertyClass.cs

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

namespace DelegateExample
{
    public class PropertyClass
    {
        public PropertyClass(string name="Default Name")
        {
            Name = name;
        }

        private string _name;
        public string Name 
        { 
            get
            { 
                return _name;
            }
            set
            {
                if (Changed != null)
                {
                    EventArgsClass objEventArgs = new EventArgsClass();
                    objEventArgs.OldValue = _name;
                    objEventArgs.NewValue = value;
                    Changed(this, objEventArgs);
                }
                _name=value;
            }
        }

        public event PropertyChanged Changed;
    }
}


DelegateClass.cs

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

namespace DelegateExample
{
    public delegate void PropertyChanged(object sender, EventArgsClass args);
}

EventArgsClass.cs

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

namespace DelegateExample
{
    public class EventArgsClass:EventArgs
    {
        public string OldValue { get; set; }
        public string NewValue { get; set; }
    }
}


No comments:

Post a Comment