Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to allocate an object on the stack with C#

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 (:

like image 286
Poni Avatar asked Nov 05 '10 00:11

Poni


People also ask

How is stack allocated in C?

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.

Can we allocate variables 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.

Are C arrays allocated on the stack?

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.


2 Answers

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.

like image 175
aqwert Avatar answered Oct 01 '22 23:10

aqwert


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.

like image 34
Femaref Avatar answered Oct 02 '22 00:10

Femaref