06-06-2013, 04:03 PM
Structure and Enumerations
Structure.pptx (Size: 71.67 KB / Downloads: 32)
Structures
Structure are similar to class in C# , but structure are value type and classes are reference type
Value type stores in stack of memory
Advantages of structure as compare to class:
They are created much more quickly than heap-allocated types.
They are instantly and automatically deallocated once they go out of the scope
Copying structs
We can also copy the values from one structure to another
Eg: Student s2;
S2=s1;
That will copy the value from s1 to s2
Note that structures data member are private by default, so it can not be accessed outside the structure definition
Structure with Methods
We can assign value to structure member by structure object.member
We can also assign value to data member using the constructors
A constructor is a method which is used to set values of data members at the time of declaration
It has the same name as structure name
Note: Parameter less constructor is not allowed
Value and Reference Types
Structs are value types, while classes are reference types, and the runtime deals with the two in different ways
When a value-type instance is created, a single space in memory is allocated to store the value
Primitive types such as int, float, bool and char are also value types, and work in the same way
With reference types, however, an object is created in memory, and then handled through a separate reference
Memory Allocation
The Common Language Runtime allocates memory for objects in two places: the stack (struct)and the heap (class)
The stack is a simple first-in last-out memory structure, and is highly efficient
When a method is invoked, the CLR bookmarks the top of the stack, the method then pushes data onto the stack as it executes
When the method completes, the CLR just resets the stack to its previous bookmark—“popping” all the method’s memory allocations