If stackalloc
is used with reference types as below
var arr = stackalloc string[100];
there is an error
Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')
Why is so? Why CLR
cannot declare pointer to a managed type?
The "problem" is bigger: in C# you can't have a pointer to a managed type. If you try writing (in C#):
you'll get:
Now,
stackalloc T[num]
returns aT*
(see for example here), so clearlystackalloc
can't be used with reference types.The reason why you can't have a pointer to a reference type is probably connected to the fact that the GC can move reference types around memory freely (to compact the memory), so the validity of a pointer could be short.
Note that in C++/CLI it is possible to pin a reference type and take its address (see pin_ptr)