Illustration of Operator Keyword stackalloc with Examples in C# (C Sharp)Why do you prefer C# when compared to C++? You might come up with different answers for it. I have mentioned two answers for this question which are related to this article discussion:
C++
doesnt bother about code management but C# does As mentioned above, C# has all its code managed in heap and its memory management is done automatically by garbage collection. In general, usage of pointers is dangerous as it gives way to malicious code. But C++ encourages Users to use pointers. But C# doesnt do that. C# will not allow Users to directly access the memory via coding. However there are situations when pointer usage is really needed to perform optimizations and few other activities. In those cases, C# gives the flexibility to use pointers but at Users risk. User has to mark the code using pointers as unsafe code and while compiling, User has to explicitly mention /unsafe option. Here is a simple example in which a block of code is marked as unsafe: public class
sampleClass { This example doesnt demonstrate the importance of pointers. It is just used to show the syntax and usage of unsafe code. Unsafe code will not be managed in heap and it will not be automatically garbage collected. Then where do you store it? How do you manage memory for it? Block of memory accessed in unsafe code will be allocated in the stack. This allocation is taken care of using stackalloc keyword. Assume that
you are using array of pointers in your unsafe code for which memory has
to be allocated in the stack. How do you do it using stackalloc keyword?
Here is a code sample: In this example, you allocated block of memory for an array containing 15 elements in the stack. Now one question might arise to you, when will this memory be freed? You dont have any automatic garbage collection happening here. However, memory is freed when the control is returned from the function in which the allocation has happened. Limitations in using stackalloc Keyword: This
keyword should only be used inside unsafe code context
|