I think it’s impossible at the language level.
The fact is that C # is a safe language. Unlike languages ​​like C and C ++, in which you can do anything and get dangling pointers, C # will not let you do this. (The result of this is, for example, the impossibility of stack disruption attacks on .NET applications.)
If it were possible to allocate memory on a stack, and memorize a pointer to it in a class field, then this object could survive the stack frame to which it refers, and you would get access to someone else's memory. Such a secure language is not allowed.
OK, you can bypass the limitations of the language, and turn it into C using an unsafe context. In unsafe-context, you can still paste the pointer into IntPtr and save it to the class in this form.
class UnsafeContainer { public IntPtr data; } class Program { static UnsafeContainer container; static unsafe void Main(string[] args) { int* addr = stackalloc int[100]; container = new UnsafeContainer { data = (IntPtr)addr }; } }
With this coding, you lose all the benefits of a safe language, and acquire the same undefined behavior as in C ++. I hope that you really need it very much . At the slightest error in unsafe code, expect problems in completely unrelated places, as is usually the case with UB.