This sounds like something you'd use a C/C++ union for. That is (if I remember my C):
union Thing
{
int iThing;
uint uThing;
char * stringThing;
double doubleThing;
};
That takes up as much memory as the largest type defined in it. So here I guess it'd be 8 bytes (for the double).
If you know what the type of the thing is, you can access the corresponding field:
Thing myThing = GetThing();
int i = myThing.iThing; // if you know it's an int
How you know its type is up to you.
Anyway, as you probably know by now, there's no such thing as a union in C#, but you can simulate one very effectively with the StructLayout
attribute found in System.Runtime.InteropServices:
[StructLayout(LayoutKind.Explicit)]
struct Thing
{
[FieldOffset(0)]
int iThing;
[FieldOffset(0)]
uint uThing;
[FieldOffset(0)]
string stringThing;
[FieldOffset(0)]
double doubleThing;
}
You can create an array or a List
of those, no problem. Of course, this is a value type, so you have to keep in mind the value type semantics. Also note that although this structure is only 8 bytes in size (or however large the biggest value type you store is), it contains a reference to a string, which is stored on the heap. That is, the cost of a string is 4 bytes (8 in 64-bit) plus the storage for the string itself.
There are more efficient ways to store strings, by the way. How you store them depends on if you'll want to modify them and how quickly you need to reference them, but you can easily save very close to 50% of the space required by .NET to store strings in English and most western European languages.