// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.IO; using Vajhoej.Record; namespace Advanced { [Struct] public class Data { [StructField(N=0,Type=FieldType.INT4)] public int Id; [StructField(N=1,Type=FieldType.INT1)] [Selector] [SubType(Value=1,Type=typeof(DataA))] [SubType(Value=2,Type=typeof(DataB))] [SubType(Value=3,Type=typeof(DataC))] public int Type; } [Struct] public class DataA : Data { [StructField(N=2,Type=FieldType.INT4)] public int V; public override string ToString() { return string.Format("(A:{0},{1})", Id, V); } } [Struct] public class DataB : Data { [StructField(N=2,Type=FieldType.INT1)] public int Count; [ArrayField(Elements=0)] [StructField(N=3,Type=FieldType.INT4)] public int[] A; public override string ToString() { return string.Format("(B:{0},{1})", Id, string.Join(" ", A)); } } [Struct] public class DataC : Data { [StructField(N=2,Type=FieldType.FIXSTRNULTERM,Length=8,Encoding="ISO-8859-1")] public string S; public override string ToString() { return string.Format("(C:{0},{1})", Id, S); } } public class Program { public static void Main(string[] args) { byte[] b = { 0x01, 0x00, 0x00, 0x00, // Id = 1 0x01, // Type = DataA 0x11, 0x00, 0x00, 0x00, // V = 17 0x02, 0x00, 0x00, 0x00, // Id = 2 0x03, // Type = DataC 0x41, 0x42, 0x43, 0x00, 0x00, 0x00, 0x00, 0x00, // S = "ABC" 0x03, 0x00, 0x00, 0x00, // Id = 3 0x02, // Type = DataB 0x03, // Count = 3 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00 }; // A = 1 2 3 StructReader sr = new StructReader(b); while(sr.More) { Data o = sr.Read(typeof(Data), null, null, (ctx, n) => { if(n == 3) { DataB o2 = (DataB)ctx; o2.A = new int[o2.Count]; return o2.Count; } else { return -1; }} ); Console.WriteLine(o); } } } }