.NET Inside Out Part 17 — Abusing types to serialize non-serializable type

This is the seventeenth part of the .NET Inside Out series. For your convenience you can find other parts in the table of contents in Part 1 – Virtual and non-virtual calls in C#

Last time we saw how to abuse type system. Today we are going to do this to serialize non-serializable type (kind of).

Let’s go with this:

Output:

Nothing surprising. We have a root object with non-serializable child and we get exception when we try serializing it.

Let’s now do similar thing as last time. Let’s create a mirror type with same binary structure but serializable:

Output:

Okay, so we replace the instance with manual memory manipulation. We then call method on the root to delegate to child which is now of different type. However, methods are called correctly (as last time) and we can now serialize the tree.

So we can see that in theory we can rebuild the graph on the side, add attributes where needed and serialize everything. To deserialize we would need to do the opposite — read the graph and then create mirror objects of original types.