Alex Rivera | Logout

C# abstract struct

Asked 2011-02-15T18:36:12.493
13

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 a struct because it has to be a value type. And I need inheritance because I need a generic array and methods that I can garantee are there.

I think an example will go a long way, so heres some code that won't compile, but shows what I want to achieve;

    abstract struct Vertex
    {
       abstract int SizeInBytes;
       abstract void SetPointers();
    }
    struct ColorVertex : Vertex
    {
       Vector3 Position;
       Vector4 Color;

       override int SizeInBytes //static
       {
          get { return (3 + 4) * 4; }
       }
       override void SetVertexPointers() //static
       {
           ...
       }
    }

class main
{
   static void main()
   {
      Vertex[] verts = new Vertex[3];
      for(int i = 0; i < 3; i++)
          verts[i] = new ColorVertex();

      verts[0].SetVertexPointers(); //should call ColorVertex.SetVertexPointers

      externalAPIcall(verts);
   }
}

EDIT:

The reason I need value types is so that I can make an array of them, and pass it to OpenGL as a vertex buffer. For this, the data needs to be directly contained in this array.

I'd be surprised if this were simply not possible to achieve.

Edit
Report

1 Answer

0

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.

answered 2011-02-15T19:52:39.980

Your Answer