0

Is it possible in .NET to define a struct with a variable number of ints?

I have collections of objects that have different number of ints. Now, each collection would have a consistant number of ints. So, I'd have one collection with structs of 1 int, another collection with structs of 3 ints, another with 7 ints, etc. I rather not define individual structs for each type or have to create an array to hold the collection so I'm wonder if there is some way to define the dynamic struct.

The reason for not wanting to use an array is the collection is contained with a parent struct

public struct ParentStruct<T>
{
    public double Timestamp;
    public T Value;
}

I'd perfer not to have the reference and not to have to peform the array allocation for each struct. I'd rather the ints just be defined 'inline' (or at least all allocated when the ParentStruct is created). Not sure if it's possible or worth the effort, but thought I'd ask.

doobop
  • 4,465
  • 2
  • 28
  • 39

1 Answers1

2

The CLR does not support the notion of a variable sized value type. That would greatly defeat the value of having value types, having a known size is what makes them efficient and capable of being stored in locations other than the heap. You would have had a shot at it if generics would have allowed a generic argument that could specify the size of a fixed size buffer, but they didn't implement that. Making the type of the fixed size buffer a generic argument is possible, but surely too restrictive for what you want to do. And unsafe.

You'll need to use an array. Do not fear the GC heap allocator, it is very very fast.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536