> If you use binary serialization to clone, you're halfway to copy/paste, if > that's a > goal. If a class is properly clonable, it ought to be > serializable/deserializable, it > seems to me. Then you can kill two birds with one stone: implement Iclonable > in > terms of binary serialization. If a class derives from MarshalByRefObject, it > probably shouldn't be clonable, but I don't want to be dogmatic about it.
There are two important drawbacks about cloning by serialization that one should be aware of: 1- Performance: Using BinaryFormatter is much slower than a manual implementation of Clone, and it's probably also much slower than a reflection-based implementation. Of course, as "slow" is relative, that's only an issue if you need to do a lot of cloning within tight time constraints. 2- Semantics: A well-behaved implementation of Clone would be expected to recursively call Clone on any ICloneable objects it contains. This does not happen when you do binary serialization, which can be an issue. Regarding the original question (in case you don't want to use serialization): You can use Reflection to check whether an object has been cloned correctly, as others have suggested, but as you've noticed, this only moves the problem to the issue of setting all fields of an object prior to testing. However, this is something you can ensure in your test: if you have a reflection-based comparer, you can not only test whether the object has been cloned correctly, but also that the source object is not equal to a "default" one. Illustrative code: [Test] public void Clone() { MyClass source = GetCloneTestSource(); MyClass defaultObject = new MyClass(); Assert.IsFalse (ReflectionBasedComparer.AreEqual (source, defaultObject), "Forgot to initialize field for cloning."); MyClass clone = source.Clone(); Assert.IsTrue (ReflectionBasedComparer.AreEqual (source, clone), "Clone failed"); } Fabian =================================== This list is hosted by DevelopMentor® http://www.develop.com View archives and manage your subscription(s) at http://discuss.develop.com