The current status of this question is a bit unclear; it was possibly a duplicate (noted in a deleted reply), but the comments suggest that this isn't quite suitable.
Re serialization slowing things down - well, unfortunately, there is no properly supported "deep clone" functionality in .NET. There is ICloneable
, but that is a: rarely used, and b: not stated as either shallow or deep. As such, the only remaining reliable way to deep clone data is to use serialization.
Re "slow as hell", can you quantify that? Which serialization mechanism was that using? (BinaryFormatter
? XmlSerializer
?). For info, you might be interested in protobuf-net, which is a pretty fast and efficient alternative binary serializer (and which offers a very handy T DeepClone<T>(T)
method) - however, it only works with classes that are marked in specific ways (for example, it can use either [DataContract]
markers, or the bespoke [ProtoContract]
markers). It is quicker than the inbuilt serializers, though.
The only other viable option is to write you own, per-type, deep copy routine, and perhaps pass that in (as a Func<T,T>
or Converter<T,T>
delegate) to your extension method.
If you only want a shallow copy, things are easier, as you can use reflection etc. Here's an option that creates a shallow copy using a compiled Expression
(.NET 3.5) for improved performance.