VALUE types are stored in one location in stack memory.
Primitive types such as int, bool, float, char are value types.
Structs are value types. Structs are cut down classes. Must use Struct keyword instead of class. Structs do not support inheritance. They reside in stack memory which can run faster than things stored in heap.
Runtime deals with the actual data so it is more efficient.
Reference types are stored in heap memory. The object is created in memory and then handled through a reference, similar to a pointer.
Classes are reference types. They are less efficient. Classes support inheritance.
Example value types:
int i = 1;
int j = i;
i++;
what is the value of j?
when you assign the value of i to j, it makes an actual copy of the value so j = 1; so when i is incremented, it doesn't affect the value of j; therefore, j = 1 and j does not = 2.
Example reference types:
class Form()
{
string Text;
}
Form myForm = new Form(); // this creates two stores of memory: 1) ref to object 2) the object itself
Form myForm; // this breaks down the above to see clearer 1) reference to object is created
myForm = new Form(); // object is created in memory
Test (myForm);
void Test (Form f)
{
f.Text = "hello"; // myForm's caption changes because myForm and f point to the same object
f = null; // myForm is intact because only a copy of the reference has been nullified/erased; myForm still holds its original reference to the object
}
http://www.albahari.com/valuevsreftypes.aspx
No comments:
Post a Comment