Unlike some programming languages you might be familiar with, C# has two varieties of data types: value and reference.
It's important to know the difference if performance is important to your application, or if you are interested in how C# manages data and memory.
When a variable is declared using one of the basic, built-in data types or a user defined structure, it is a value type. An exception is the string data type, which is a reference type.
A value type stores its contents in memory allocated on the stack. For example, in this case the value 42 is stored in an area of memory called the stack.:
Example:
int x = 42;
When the variable x goes out of scope because the method in which it was defined has finished executing, the value is discarded from the stack.
Using the stack is efficient, but the limited lifetime of value types makes them less suited for sharing data between different classes.
In contrast, a reference type, such as an instance of a class or an array, is allocated in a different area of memory called the heap. In the example below, the space required for the ten integers that make up the array is allocated on the heap.
Example:
int[] numbers = new int[10];
This memory isn't returned to the heap when a method finishes; it's only reclaimed when C#'s garbage collection system determines it is no longer needed. There is a greater overhead in declaring reference types, but they have the advantage of being accessible from other classes.
Summary
In this article I try to clear concept of Value and Reference Types. I hope after reading this article you will be able to use this in your code. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.
No comments:
Post a Comment