Saturday, June 25, 2016

Value and References types in C#


Value Type and References types in C#





Value Types

All numeric data types. For e.g. int x = 10
Boolean, character and Date
All structures even if their members are reference type
Enums


Reference Types

String (Internally the text is stored as a sequential read-only collection of character objects)
All arrays, even if their elements are value type
Class types such as Form
Delegates
*You must use New operator keyword when you initialize reference type.

Elements that are not Types
Namespaces
Modules
Events
Properties and Procedures
Variables, constants and fields.

In Depth
1. Value Type: A value type stores its contents in a Memory allocated on the stack. When you create a value type, a single space in memory is allocated to store the value and that variable directly holds a value. If you assign it to another variable, the value is copied directly and both the variables work independently. 
*Value type can be created compile time and stored in stack memory, because of this Garbage Collector can’t access Stack
2. Reference Type: Reference Type are used by a reference which holds a reference to a object itself. Because reference types represents the address of the variable rather than data itself, assigning a reference variable to another variable doesn’t copy the data, insteadit creates a second copy of the reference, which refers to the same location of the heap as the original value (Can be marked for garbage collection)

Value type and reference type



No comments:

Post a Comment