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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jaganathan BantheswaranRank #170 · 14.1K reputationPosted Jul 6, 2011, 3:00 AM EDT
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.
Zoran HorvatRank #792 · 2.9K reputationPosted Jul 6, 2011, 3:21 AM EDT
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.
VulpesRank #55 · 29.2K reputationPosted Jul 6, 2011, 2:02 PM EDT