In Binary Serialization (C #) how to ignore non-serializable fields in a serializable object?


I have a class which is marked with [Serializable] attribute. This class is having many fields of different types. Most of the types being referred by this class have the [Serializable] attribute but a few of them don't have this attribute.

Binary Serialization fails in the above scenario, which is expected.

I have simplified the problem in the above description. In reality I am dealing with a large enterprise application which has complex object hierarchy and deep down into the hierarchy there are a few windows types that cannot be serialized and the Binary Serialization fails. I want a solution for this.

Is there a Custom Binary Serializer available which can skip the fields that can not be serialized?

Note: I am aware of this concept: How do you identify the field that is causing binary serialization to fail in .NET?

I am looking for a more elegant solution.

You can add the [NonSerialized] attribute on a field to skip it entirely once you've identified that it cannot be serialized.

If it's types much further down the hierarchy that you don't have control over that are causing this then what I'd suggest is duplicating the structure of the classes/structs in question sans-unserializable-fields and using something like automapper to deep-copy the values to your new classes, and then serialize the end result.