How can I achieve inheritance (or similar) with structs in C#? I know that an abstract struct isn\'t possible, but I need to achieve something similar.
I need it as
Maybe you can use a "union" type:
enum VertexType : byte {
Vertex,
ColorVertex
}
[StructLayout(LayoutKind.Explicit)]
struct Vertex {
[FieldOffset(0)]
public readonly VertexType Type;
[FieldOffset(1)]
public readonly int SizeInBytes;
public Vertex(VertexType type /* other necessary parameters... */) {
Type = type;
// set default values for fields...
switch (Type) {
// set the fields for each type:
case VertexType.ColorVertex:
SizeInBytes = (3 + 4) * 4;
// other fields ...
break;
default:
SizeInBytes = 2; // or whatever...
// other fields ...
break;
}
}
// other fields with overlapping offsets for the different vertex types...
}
Just remember to make it immutable and to access only the fields that make sense for each type.