Search code examples
c#stackalloc

Why stackalloc cannot be used with reference types?


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?


Solution

  • The "problem" is bigger: in C# you can't have a pointer to a managed type. If you try writing (in C#):

    string *pstr;
    

    you'll get:

    Cannot take the address of, get the size of, or declare a pointer to a managed type ('string')

    Now, stackalloc T[num] returns a T* (see for example here), so clearly stackalloc 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)