#186 – Value Types on the Heap

Value types are normally allocated on the stack. They can, however, be allocated on the heap–when they are declared within an object.  When an object is instantiated, memory for the entire object, including all of its data, is allocated on the heap.

For example, assume we define a Person class with some properties that are value types (int) and some that are reference types (string).

    public class Person
    {
        string FirstName;
        string LastName;

        int Age;
        int HeightInInches;      // also on heap

        public Person(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }
    }

When you create an instance of the Person object,

            Person p = new Person("Zsa Zsa", "Gabor");

the Person object is created on the heap and all of its data members, including the Age and HeightInInches value types, are also on the heap.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #186 – Value Types on the Heap

  1. Pingback: #188 – Objects Are on the Heap, References to Objects Are on the Stack « 2,000 Things You Should Know About C#

  2. Efim says:

    As described here:http://stackoverflow.com/questions/815354/why-are-structs-stored-on-the-stack-while-classes-get-stored-on-the-heap-net value types allocated on heap if they are:
    if they are fields on a class
    if they are boxed
    if they are “captured variables”
    if they are in an iterator block

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: