Example for Delegate in C#

namespace testobserver
{
    public delegate void ChangeRelationshipStatusDelegate(string status);

    public class Boy
    {
        public string relationshipStatus { get; set; }

        public void Propose(ChangeRelationshipStatusDelegate relationshipStatusChange)
        {
            relationshipStatusChange("enaged");
        }
    }
}
namespace testobserver
{  
    public class Girl
    {
        public string relationshipStatus { get; set; }

        public void ChangeStatus(string status)
        {
            relationshipStatus = status;
        }
    }
}

using System;

namespace testobserver
{
    class Program
    {
        static void Main(string[] args)
        {
            Girl kim = new Girl();
            kim.relationshipStatus = "single";
            Console.WriteLine("before propose: " + kim.relationshipStatus);
            Boy kanye = new Boy();
            kanye.Propose(new ChangeRelationshipStatusDelegate(kim.ChangeStatus));
            Console.WriteLine("proposal notified to Girl and proposal accepted: " + kim.relationshipStatus);
            Console.ReadLine();
        }
    }
}

Advertisements

Author: Harshani Nawarathna

Sri Lankan woman in Computing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s