MemoryPack
MemoryPack copied to clipboard
ArrayTypeMismatchException: when using collections with interfaces
Hello, I am trying to serialize a class that holds a collection of objects given by an interface. But I always get ArrayTypeMismatchException Attempted to access an element as a type incompatible with the array. Any idea what I am doing wrong?
[Fact]
public void CollectionOfInterfaces()
{
var f = new DynamicUnionFormatter<IMyInterface>(
(0, typeof(MyClass)));
MemoryPackFormatterProvider.Register(f);
var one = new MyClass() { MyProperty = 999 };
var myClass = new MyListHolder
{
Bases = new []{ one }
};
var bin1 = MemoryPackSerializer.Serialize(myClass);
}
[MemoryPackable]
public partial class MyListHolder
{
public IReadOnlyCollection<IMyInterface> Bases { get; init; }
}
[MemoryPackable(GenerateType.NoGenerate)]
public partial interface IMyInterface
{
}
[MemoryPackable(GenerateType.Object)]
public partial class MyClass : IMyInterface
{
public int MyProperty { get; set; }
}
Thank you! I've confirmed, it is bug of implementation, if exists array's covariance throws runtime exception. I'll fix it.
For example, if you change to this will work fine.
var myClass = new MyListHolder
{
Bases = new IMyInterface []{ one }
};
Also you can change like this
var myClass = new MyListHolder
{
Bases = [one]
};
This issue is stale because it has been open 180 days with no activity. Remove stale label or comment or this will be closed in 30 days.
@neuecc Should this problem (confirmed by you) really be closed?
ah, no, need to fix sorry.