Does anyone want a framework/class which allows me to clone by values .Net objects? I’m only interested with public read/write properties (namely DataContracts), and I don’t care if references are resolved correctly (i.e. collecions which contains the same instance of item twice).
I tried serialization trick via DataContractSerializer (serialize to XML and back), wrote reflection-based cloning class (sometimes faster/sometimes slower), and was wondering if someone wrote a helper class which can do this via Emit and not reflection. As for now emitting IL is a little to much for my little brain, but I guess this would be the ultimate solution. Unless someone knows an alternative method which is faster than DataContractSerializer.
If you are talking about an object tree/graph:
Writing specific IL to serialize an object is tricky. IMO, your best bet is to look at a full serialization, like how
DataContractSerializerwould work – but not necessarily with that engine.For example, protobuf-net has a
Serializer.DeepClone<T>method that might help. It should be faster thanDataContractSerializer, at least. At the current time, you need to add some clues for the serializer (even if just[ProtoContract(ImplicitFields=ImplicitFields.AllPublic)]) – however, the current (incomplete) work-in-progress offers POCO support without attributes.If you are talking about individual objects:
There are fairly simple things you can do here with
Expressionin .NET 3.5; build a dynamicExpressionbased on reflection, and call.Compile(). MiscUtil has this already:With .NET 2.0/3.0 (without
Expression) you might consider HyperDescriptor for similar purposes.