tags:

views:

39

answers:

2

For one of the classes I have, it's necessary to implement a clone method. So I'm trying to figure out if I need to copy the events of the class by reference or by value.

For example, let say you have the following:

Ball ballOne = new Ball();
ballOne.Bounce += new EventHandler(ballOne_Bounce);

Ball ballTwo = ballOne.Clone();

How should I write the Clone method so the Bounce event for ballTwo is triggered?

Thanks, Tyler

+1  A: 
public Ball Clone() {
    ... create the new instance ...
    clone.Bounce = Bounce;
    ... set more properties ...
    return clone;
}

Delegates are reference types in .NET, and they're also immutable, so "reference vs. value" isn't meaningful. If you want to copy the event delegate, just copy it (i.e., copy the reference).

Joe White
But he doesn't want to copy the event delegate because that will point to ballOne not ballTwo right?
Graphain
The delegate doesn't know anything about ballOne. It only references ballOne_Bounce, which is presumably on some other object (the form?).
Joe White
A: 

This really depends on how you're using the Ball object and how you're going to go about cloning it. It also depends greatly on what the listener is doing.

If you want ballOne and ballTwo to have the exact same registered event listeners, you can just pass the event handler reference from ballOne to ballTwo and they should both work. Keep in mind, though, that if you then add a new event listener to ballOne, ballTwo won't also get it.

I'm not sure what you're trying to do, but this can lead to memory leaks and lots of hassles when you've got lots of cloned balls all over the place and you won't know which ones have which event listeners.

You might be better off creating a method on whatever class is holding the balls so that it can add the appropriate event listeners.

 public class Box
{

    public void InitializeBalls()
    {
        Ball ballOne = new Ball();
        this.RegisterBall(ballOne);

        Ball ballTwo = ballOne.Clone();
        this.RegisterBall(ballTwo);

    }


    public void Ball_Bounce()
    {
    }

    public void RegisterBall(Ball ball)
    {
        ball.Bounce += Ball_Bounce;
    }

}

public class Ball
{

    public event BounceEventHandler Bounce;
    public delegate void BounceEventHandler();


    public Ball Clone()
    {
        Ball clonedBall = null;
        // Do some fancy clonin'
        return clonedBall;

    }

}
rossisdead