views:

127

answers:

2

Let's say, hypothetically (read: I don't think I actually need this, but I am curious as the idea popped into my head), one wanted an array of memory set aside locally on the stack, not on the heap. For instance, something like this:

private void someFunction()
{
    int[20] stackArray; //C style; I know the size and it's set in stone
}

I'm guessing the answer is no. All I've been able to find is heap based arrays. If someone were to need this, would there be any workarounds? Is there any way to set aside a certain amount of sequential memory in a "value type" way? Or are structs with named parameters the only way (like the way the Matrix struct in XNA has 16 named parameters (M11-M44))?

+3  A: 

What you want is stackalloc; unfortunately, you can only use this in unsafe code, which means it won't run in a limited permissions context.

You could also create a struct with the necessary number of variables in it for each element type, but you would need a new type for each size of 'array' you wanted to use

thecoop
Hm, what about a primitive LinkedList? On your struct set previous / next struct of same type...you don't get ICollection semantics, but it could be enough for IEnumerable...
flq
Thanks for the reply. Yes, are struct based LinkedLists possible? And do you have an idea why there isn't a Safe stack based array option in .NET?
Bob
@Frank: You can't do this - when I try to compile a recursive struct, I get a 'CS0523: Struct member <member info> causes a cycle in the struct layout'
thecoop
@thecoop What if you make your node nullable?
Bob
`Nullable<T>` is still a struct, so it wont work. Think about it - when you declare a recursive struct, you're basically asking the CLR to allocate space for an infinite list of structs.
thecoop
Thanks for the help. I don't know why a stack based array isn't possible in safe code though. I can't see how an array is much different than a struct or why this isn't possible...but that's another matter altogether I guess
Bob
Thanks for checking out...it does make sense as you explain it. Clever compiler!
flq
A: 

You can create a fixed array in a structure or class (use the C# fixed keyword for this). This will do exactly what you need. The structure needs to be defined as unsafe to be able to do this.

Steven