Dan Dorey wrote:
I've implemented the ICloneable interface on one of my class. I've
written this simple code in two different ways and I think both should
work but it's not the case and I'm curious to understand why.
You haven't posted complete code. For best results, you need to post a
concise-but-complete example of code that demonstrates the problem. In
this case, that would mean a minimal class posted with two complete
methods to clone, one for each technique you're using.
For what it's worth, it's my opinion that the code you posted isn't
really cloning anyway, so you shouldn't call it cloning. I suppose
there's some wiggle-room semantically, but so little of the original
object remains that I think it's very misleading in the code to use the
term "clone" to describe the operation.
And finally, some specific comments (none of which suggest what the
problem is, as far I know):
The working method:
CallflowBase ret = null;
ret = this.MemberwiseClone() as CallflowBase;
There's no need to initialize the variable to null if you're just going
to set it immediately after.
Otherwise, this seems fine and it should return a new instance of your
object, assuming you don't change "ret" later and return the value in "ret".
[...]
/* I thought it would be simpler to just new up a new class in this
case as I don't really want to copy most of the members */
I think so too. And because you don't want to copy most of the members,
I wouldn't actually call it a "clone". :)
CallflowBase ret = new CallflowBase();
This seems fine and should return a new instance of your object (with
the same caveats noted above).
[...]
But it appears that this method of cloning fails since I end up
pointing to the same object. Am I missing something obvious here?
If so, you didn't post the code that is causing the problems. At least,
not as near as I can tell.
In both versions, you initialize a variable "ret" to be a new instance
of your object. So, it seems that the problem is not in the code you
posted. Some suggestions as to what _might_ be the problem:
* You are not actually returning that value held by the "ret" local
variable. What value you are returning, I can't say, since you didn't
post a complete example of the code.
* You are incorrectly determining that you "end up pointing to the
same object". Do you actually have a reference to the same object? How
exactly did you make that determination? When you clone an object,
obviously the resulting object can in a lot of ways look a lot like the
original. :)
There are other ways you may have made a mistake, but it's not really
possible with the code you posted to say for sure, I think.
Pete