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 (:
If you changed it to a value type using
structand 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 usevarto eliminate the double use of the type nameOtherwise, take C# as it is since the GC does a great job.