views:

198

answers:

4

Can I create an object of my class in stack regarding .net and C#? For example:

class abc { int i=1; } 
abc a1=new abc();

Now, here the object is created in heap. So, is there any way to create the object in stack memory of ram if the size of object is not big?

+4  A: 

.NET reference types always live on the GC heap. It's not possible to have them elsewhere. Even C++/CLI that supports things like

System::Random rnd;
rnd.Next();

that looks like stack variables, actually creates the Random class, on the GC heap (and calls its Dispose method at the end of the block if it implements IDisposable.)

That said, as Eric Lippert says, the stack is an implementation detail and you should primarily care about reference or value semantics of the types you create.

Mehrdad Afshari
A: 

As Mehrdad says, reference type instances (objects) are stored on the heap, along with things like static variables. Local variables and the like are stored on the stack.

Iain Hoult
A: 

I don't know why you need an object on the stack instead of the heap. The main reason for that (at least the main reason I know) is RAII. The compiler in c++ guarantees that each object created on the stack is destroyed when it leaves scope.

In C# you archive the same thing with the using-statement: http://msdn.microsoft.com/en-us/library/yh598w02.aspx

Tobias Langner
A: 

If you use struct instead of class, you create a value-type that will be created on the stack. There's lots of things to consider about this. The book Framework Design Guidelines doesn't make a concrete suggestion, but indicates it's probably best to benchmark the differences and determine if it's really worth implementing a value-type.

OwenP