Hi
any one tell me that when i using Structs and structs is value type (means it will store in Stack right...?) and when i make its object of struct where it will store heep side either stack side...?
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Jul 6, 2011, 6:02 PM
Zoran HorvatPosted Jul 6, 2011, 7:21 AM
Value type instance is allocated in place where declared. Reference type instance will always be allocated on heap, and on place of declaration only a 4- or 8-byte scalar will be allocated (depending on CPU) which merely keeps the address on the heap where the block begins.
Hence, value type can be allocated as part of a stack frame if declared as a local variable in the method. Or it can be allocated on the heap if declared as part of a larger instance which goes to the heap, e.g. the simplest case is if declared as a field in a class.
For example, if you declare a struct Point{ int x; int y }, and do this: Point p = new Point(5, 3), that would surely go onto stack. But if you do this: Point[] p = new Point[40]; then that would go to heap because array is a reference type. In more details, one instance of Point takes four bytes for x and four bytes for y. So first instantiation of only one Point instance will take 8 bytes on stack, as part of the current stack frame. In second case, when array of 40 points is allocated, that would allocate 40x8=320 successive bytes on heap.
The example with array of 40 points also raises the question of default constructors in structures. C# does not allow parameterless constructors on structures (though CLR does), but rather leaves CLR to allocate array of structures and to zero them out in a single assembler instruction, which is extremely efficient.
Jaganathan BantheswaranPosted Jul 6, 2011, 7:00 AM
When you call the New operator on a class, it will be allocated on the heap. However, when you instantiate a struct, it gets created on the stack. This will yield performance gains. Also, you will not be dealing with references to an instance of a struct as you would with classes. You will be working directly with the struct instance. Because of this, when passing a struct to a method, it's passed by value instead of as a reference.