The main problem, I see, is to create "indepependent copies" of the
reference types.
I imagine a recursive method that, given an instance of a class, will create
a copy of it and all of its value type values. But when it finds a reference
type, it should run this method recursively to create a new copy, and so,
and so...
BUT. (and now I think I'm really understanding the purpose of ICloneable) we
couldn't do this beacause not all classes have a default argument-less
constructor. So, we couldn't know in advance HOW the instance is to be
created. And as the "new" keyword is mandatory in order to allocate new
memory for the new instance (and thus creating independent instances) .
In an ideal escenario, all the classes would have a Clone method, which
creates a shallow copy and calls Clone method of every reference type, or
manages to do the same with strings, which are also ref types.
I'm just making questions to myself. Feel free to post your comments.
Regards...
Gabriel Lozano-Morán said:
I have taken a look at several classes in the .NET framework that implement
the IClonable interface. What these actually do is create a new object
instance using parameterized constructors. What you could try but I am not
sure that this will work is mark your class with the [Serializable]
attribute and then serialize it to a memory stream and then deserialize it.
Gabriel Lozano-Morán
Software Engineer
Sogeti
Tiësto said:
Gracias Gabriel. I see this topic is a little complex, as I've seen many
different positions about where/how long/why we should use IClonable
interface or not. Some people say it will be deprecated on framework 2.0,
as you never know if it returns a shallow copy or a deep copy. I thought
there would be a method like MemberwiseClone(), with the diference that
it could create a real copy of the reference types, creating new memory
locations and copying the values from the first one.
I see i have to implement that by myself.
Thanks anyway!