using System.Collections; using System.Diagnostics.CodeAnalysis; using MemoryPack; [MemoryPackable] public partial class MyCustomContainer : IEnumerable { [MemoryPackInclude] private List items = new(); public void Add(T item) => items.Add(item); public IEnumerator GetEnumerator() => items.GetEnumerator(); } [MemoryPackable] [MemoryPackUnion(0, typeof(MyDerivingType))] [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public partial interface IMyInterface { string MyProperty { get; set; } } [MemoryPackable] [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public partial class MyDerivingType : IMyInterface { public string MyProperty { get; set; } public int MyOtherProperty { get; set; } public void MyMethod() { } } [MemoryPackable] [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public partial class MyContainingClass { public MyCustomContainer MyData { get; set; } } class Program { static void Main(string[] args) { IMyInterface someData = new MyDerivingType(); someData.MyProperty = "Hello World!"; MyContainingClass containingClass = new(); containingClass.MyData = new MyCustomContainer(); containingClass.MyData.Add(someData); byte[] data = MemoryPackSerializer.Serialize(containingClass); File.WriteAllBytes("bytes.bin", data); MyContainingClass deserialized = MemoryPackSerializer.Deserialize(File.ReadAllBytes("bytes.bin")); foreach (IMyInterface item in deserialized.MyData) { Console.WriteLine(item.MyProperty); } } }