Search code examples
c#serializationreflectiondeserialization

How to dump and load object with private fields in c#?


I want to refactor a legacy project and have a huge method. No one knows what the method does exactly. My plan is to dump the objects from the parameter list and the returned object and load them again for a test. In that way I can assure that while refactoring nothing changes.

But the specific objects have private fields and I can't change them (to make them serializable). I can use something like ObjectDumper to dump the object with private fields but I don't know how to load the object again.

Do anyone know a library that does that for me?


Solution

  • You can use binary serialization:

    
    MemoryStream ms = new MemoryStream();
    
    #pragma warning disable 618
    var formatter = new BinaryFormatter();
    formatter.Serialize(ms, data);
    #pragma warning restore 618
    
    

    You'll get a warning that this method is obsolete, but it works just fine in all environments I use (certainly up to .NET 6.0).