Unions with Inheritance
I'm trying to use a union with inheritance so I can avoid duplicating some properties in the data structures. Here is a stripped down example.
[Union(typeof(B),typeof(C))]
public abstract class A
{
[UnionKey]
public abstract string Type { get; }
[Index(0)]
public virtual string Name {get;set;}
}
[ZeroFormattable]
public class B : A
{
public override string Type {get { return "B"; } }
[Index(1)]
public virtual int Val { get; set;}
}
[ZeroFormattable]
public class C : A
{
public override string Type {get { return "C"; } }
[Index(1)]
public virtual int Val { get; set;}
[Index(2)]
public virtual int Valer { get; set;}
}
Instead of having to add Val to C I want to make C inherit from B.
I made an attempt here but I ran into a few issues
// C2 must come first otherwise it becomes a B2
[Union(typeof(C2),typeof(B2))]
public abstract class A2
{
[UnionKey]
public abstract string Type { get; }
[Index(0)]
public virtual string Name {get;set;}
}
[ZeroFormattable]
public class B2 : A2
{
public override string Type {get { return "B"; } }
[Index(1)]
public virtual int Val { get; set;}
}
[ZeroFormattable]
public class C2 : B2
{
// without this it causes an StackOverflow
[IgnoreFormat]
public override string Type {get { return "C"; } }
// now in B2
//[Index(1)]
//public virtual int Val { get; set;}
[Index(2)]
public virtual int Valer { get; set;}
}
The order of the types in the Union attribute seems to matter otherwise i.e.
// if using [Union(typeof(B2),typeof(C2))]
var items = new A2[] {new B2(),new C2() { Valer = 1} };
var res = ZeroFormatterSerializer.Convert<A2[]>(items);
All the objects in res are deserialized to B2s. But switching the order to [Union(typeof(C2),typeof(B2))] and adding [IgnoreFormat] to C2's Type property makes it work.
Can you recommend a better way to structure this? I feel like I'm missing something. Thanks.
Thank you!
This is an undesirable behavior and it seems to be a issue of implementation of Union. I'll try fix.
Thanks for the quick response.
If you need a hand with testing etc. I'm happy to pitch in. But to be honest I think I'm probably a bit out of my depth with the low level stuff your working with.
Thanks again.