MemoryPack icon indicating copy to clipboard operation
MemoryPack copied to clipboard

ArrayTypeMismatchException: when using collections with interfaces

Open ptr1120 opened this issue 1 year ago • 1 comments

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; }
}

ptr1120 avatar Jul 21 '24 15:07 ptr1120

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]
};

neuecc avatar Jul 23 '24 10:07 neuecc

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.

github-actions[bot] avatar Jan 20 '25 00:01 github-actions[bot]

@neuecc Should this problem (confirmed by you) really be closed?

ptr1120 avatar Feb 19 '25 05:02 ptr1120

ah, no, need to fix sorry.

neuecc avatar Feb 21 '25 00:02 neuecc