Under the Hood of .NET Memory Management - Simple Talk
Under the Hood of .NET Memory Management - Simple Talk
Under the Hood of .NET Memory Management - Simple Talk
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Chapter 4: Common <strong>Memory</strong> Problems<br />
Types<br />
The type system in .<strong>NET</strong> consists <strong>of</strong> value and reference types: a value type is a primitive<br />
or struct, and a reference type is a pointer. In practical terms, while a value type will<br />
simply represent <strong>the</strong> current value for whatever variable you are dealing with, reference<br />
types are a bit more complicated. There are two components to <strong>the</strong> data in a reference<br />
type, specifically, <strong>the</strong> reference and <strong>the</strong> actual data. The reference is stored in <strong>the</strong> stack,<br />
and it contains <strong>the</strong> memory location (in <strong>the</strong> heap) where <strong>the</strong> data is actually stored.<br />
A type itself describes <strong>the</strong> possible data that it can hold, along with <strong>the</strong> operations it can<br />
perform on that data. Every variable has a type that fully describes it, and it may also have<br />
types that provide a partial description, such as an interface.<br />
DateTime valueType = DateTime.Now;<br />
IComparable partialDescription = valueType;<br />
List referenceType = new List();<br />
IEnumerable partialDescription2 = referenceType;<br />
Listing 4.1: Switching from <strong>the</strong> type to an interface.<br />
In this example, valueType is a DateTime and so can do anything that a DateTime<br />
can do, but partialDescription is an IComparable and can only do what an<br />
IComparable can do, even though both variables have <strong>the</strong> same data and refer to <strong>the</strong><br />
same location in memory.<br />
Let's take a look at <strong>the</strong>se two main .<strong>NET</strong> types, and see how <strong>the</strong>ir nature and operations<br />
can give rise to bugs and memory leaks.<br />
87