Say I have this C# class:
public class HttpContextEx
{
public HttpContext context = null;
public HttpRequest req = null;
public HttpResponse res = null;
}
How do I declare an object of it, inside a function, which will be allocated on the stack and not on the heap?
In other words I want to avoid using the 'new' keyword for this one. This code is bad:
HttpContextEx ctx = new HttpContextEx(); // << allocates on the heap!
I know what stack/heap are perfectly and I've heard of the wonderful C# GC, yet I insist to allocate this tiny object, which is here only for convenience, on the stack.
This attitude comes from C++ (my main tool) so I can't ignore this, I mean it really ruins the fun for me here (:
Stack Allocation: The allocation happens on contiguous blocks of memory. We call it a stack memory allocation because the allocation happens in the function call stack. The size of memory to be allocated is known to the compiler and whenever a function is called, its variables get memory allocated on the stack.
The allocation and deallocation for stack memory is automatically done. The variables allocated on the stack are called stack variables, or automatic variables. Since the stack memory of a function gets deallocated after the function returns, there is no guarantee that the value stored in those area will stay the same.
Unlike Java, C++ arrays can be allocated on the stack. Java arrays are a special type of object, hence they can only be dynamically allocated via "new" and therefore allocated on the heap.
If you changed it to a value type using struct
and create a new instance within the body of a method, it will create it on the stack. However the members, as they are reference types will still be on the Heap. The language whether it be a value or a reference type will still require the new operator but you can use var
to eliminate the double use of the type name
var ctx = new HttpContextEx();
Otherwise, take C# as it is since the GC does a great job.
You can't (and shouldn't) do that. Even if you would use a struct
(which will be put on the stack), you'd have to use the new
operator for the contained classes. On a serious note, if you switch to another language, also switch your attitudes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With