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:
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:
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.
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:
keyword should only be used inside unsafe code context
to our mailing list and receive new articles Note
: We never rent, trade, or sell my email lists to Visit
.NET Programming Tutorial Homepage ______________________________________________________
to our mailing list and receive new articles
: We never rent, trade, or sell my email lists to
Visit .NET Programming Tutorial Homepage
| How does Yield Keyword of C# Use Lazy Evaluationm: Reference Types |How to Create Iterator to Process Generic List in C# | How to Use add and remove Contextual Keywords of C# | How to Use ForEach with Arrays in C# |Illustration of Operator Keywords (as, is) with Examples in C# | Illustration of Operator Keywords (new, sizeof) with Examples in C# |Illustration of Operator Keyword stackalloc with Examples in C# |Illustration of Operator Keywords (true, false) with Examples in C#|Illustration of Operator Keyword typeof with Examples in C# |List of Contextual Keywords in C#|