0

I was recently looking over this question on deep cloning in C#: How do you do a deep copy of an object in .NET?

I'm not a C#/.NET expert, so if this is completely off, someone please correct me. Why aren't people suggesting doing the following?

JObject.FromObject(theObject).DeepClone().ToObject<TheObjectClass>();

The most upvoted answers are extremely verbose solutions and I'm sure it's for a good reason, so I really want to understand why this one-liner isn't valid.

TylerH
  • 20,799
  • 66
  • 75
  • 101
jgozal
  • 1,480
  • 6
  • 22
  • 43

1 Answers1

8

But why aren't people suggesting doing the following?

JObject.FromObject(theObject).DeepClone().ToObject<TheObjectClass>();

Because not every object can be serialized to JSON. Specifically objects with circular references, or objects where you have multiple references to the same instance.

D Stanley
  • 149,601
  • 11
  • 178
  • 240