Click here to Skip to main content
15,885,546 members
Articles / Programming Languages / C#
Article

A "how to" for Delegate use as a thread safe pointer

Rate me:
Please Sign up or sign in to vote.
2.00/5 (7 votes)
24 Mar 20052 min read 47.5K   407   13   15
This article provides a real world usage example for using delegates.

Image 1

Introduction

This article provides a real world usage example of using delegates. What is a delegate, and how do I use it in my code? Think of a delegate as a thread safe pointer, providing a thread throughput to a method call on a class. I have seen a lot of theoretical examples on how to use delegates, but to get more people to use them I have created a real world example that was created as part of my professional work.

Background

I need a way to provide a thread safe pointer from a child object to a parent object, without putting the parent object in the child object as a parameter, which would cause a circular reference. I wanted to change a parameter on the parent object when the child object was changed, without having to reference the parent object directly. The solution I came up with was to use a delegate. The delegate allowed me to provide a pointer in the child object to its parent, without having to directly reference the parent.

Using the code

Notice that the parent object contains the child object:

C#
public class ParentObject
    {
        private ChangeType _changeType = ChangeType.None;
        private ChildObject _childObject;

Notice that the child object does not contain the parent, but instead two delegate types ParentSetChangeTypeDelegate and ParentGetChangeTypeDelegate:

C#
public class ChildObject 
    {
        #region Private Varaibles
        private ChangeType _changeType = ChangeType.None;
        private ParentSetChangeTypeDelegate _parentSetChangeTypeDelegate;
        private ParentGetChangeTypeDelegate _parentGetChangeTypeDelegate;
        #endregion

We have two constructors one that has no parameters, and one that accepts the ParentObject class. This provides a control for supporting the object alone or within its parent:

C#
#region Constructor
        /// <summary>
        /// 
        /// </summary>
        public ChildObject()
        {
            
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="parent"></param>
        public ChildObject(ParentObject parent)
        {
            SetParent(parent);
        }
        #endregion

The SetParent method provides a way to set up the accessors to the methods on the parent class. Notice the way we delegate the method calls from the parent class to the child. In this fashion we can provide a thread safe pointer back to the parent class, without having the parent as an actual parameter:

C#
/// <summary>
/// Set the ParentSetChangeTypeDelegate to hold an instance of the method
/// ChildObject.SetTypeOfChange for use when changing the ChangeType
/// of an object
/// </summary>
/// <param name="parent"></param>
public void SetParent(ParentObject parent)
{
    if(parent != null)
    {
        _parentGetChangeTypeDelegate =
           new ParentGetChangeTypeDelegate(parent.GetTypeOfChange);
        _parentSetChangeTypeDelegate =
           new ParentSetChangeTypeDelegate(parent.SetTypeOfChange);
    }
}

The DoChange method actually makes changes to the child and parent object via the delegates:

C#
/// <summary>
/// Sets the child's change, if the parent is availiable, then
/// sets the parents as well
/// </summary>
/// <param name="changeType"></param>
public void DoChange(ChangeType changeType)
{

    //here we find out if there is a parent object
    if(_parentGetChangeTypeDelegate != null &&
        _parentSetChangeTypeDelegate != null)
    {
        switch(changeType)
        {
            case ChangeType.Add :
                SetTypeOfChange(ChangeType.Add);
                _parentSetChangeTypeDelegate(ChangeType.Modify);
                break;
            case ChangeType.Modify :
                SetTypeOfChange(ChangeType.Modify);
                _parentSetChangeTypeDelegate(ChangeType.Modify);
                break;
            case ChangeType.Remove :
                SetTypeOfChange(ChangeType.Remove);
                _parentSetChangeTypeDelegate(ChangeType.Modify);
                break;
            default :
                break;
        }
    }

Notice when the child changes, the value of GetTypeOfChange on the parent object will change as well.

C#
line 30:    Console.WriteLine("///New Change....///");
line 32:    child.DoChange(ChangeType.Add);

Image 2

Points of interest

Run the test, and see for yourself how it works. I hope this helps someone who has had trouble finding a real world example on how to use delegates.

History

This is the first submission to CodeProject on this subject and is the first revision.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
Christopher G. Lasater

I am also a published author, please check out my book:
ISBN: 1-59822-031-4
Title: Design Patterns
Author:Christopher G. Lasater
More from my web site
Amazon.com


Comments and Discussions

 
QuestionWhere is ParentObject in source zip file? Pin
vossburton19-Sep-07 16:20
vossburton19-Sep-07 16:20 
AnswerRe: Where is ParentObject in source zip file? Pin
Christopher G. Lasater20-Sep-07 4:17
Christopher G. Lasater20-Sep-07 4:17 
GeneralGarbage collection and delegates [modified] Pin
Christopher G. Lasater28-Aug-06 19:12
Christopher G. Lasater28-Aug-06 19:12 
GeneralThread safe ?! Pin
Ralph Varjabedian3-Jul-06 22:42
Ralph Varjabedian3-Jul-06 22:42 
I do not think you understand what is meant by thread safe... D'Oh! | :doh:
GeneralRe: Thread safe ?! [modified] Pin
Christopher G. Lasater4-Jul-06 18:46
Christopher G. Lasater4-Jul-06 18:46 
GeneralI don't get the point... Pin
Bekende19-May-05 3:20
Bekende19-May-05 3:20 
GeneralRe: I don't get the point... Pin
Christopher G. Lasater19-May-05 4:07
Christopher G. Lasater19-May-05 4:07 
GeneralRe: I don't get the point... Pin
Mark A. Nicholson12-Oct-05 3:19
Mark A. Nicholson12-Oct-05 3:19 
GeneralRe: I don't get the point... Pin
Christopher G. Lasater28-Aug-06 18:58
Christopher G. Lasater28-Aug-06 18:58 
GeneralRe: I don't get the point... Pin
Christopher G. Lasater28-Aug-06 19:01
Christopher G. Lasater28-Aug-06 19:01 
GeneralRe: I don't get the point... Pin
Christopher G. Lasater19-May-05 8:45
Christopher G. Lasater19-May-05 8:45 
GeneralRe: I don't get the point... Pin
Bekende19-May-05 12:05
Bekende19-May-05 12:05 
GeneralRe: I don't get the point... Pin
Christopher G. Lasater19-May-05 12:19
Christopher G. Lasater19-May-05 12:19 
GeneralRE: &quot;how to&quot; for delegate use Pin
cdawson8r12-Apr-05 11:25
cdawson8r12-Apr-05 11:25 
GeneralRe: RE: &quot;how to&quot; for delegate use Pin
Christopher G. Lasater12-Apr-05 11:31
Christopher G. Lasater12-Apr-05 11:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.