Learning C# Part 4: Classes and Objects

Written By: Kevin Jordan

- 14 Oct 2006 -
















Description: This series aims to take a beginning programmer to an intermediate level in C#. Topics covered in Part 4 include: classes and objects, accessibility and scope, methods, constructors, static class members, namespaces, and XML commenting.

  1. Classes and Objects
  2. The Stack and the Heap
  3. Defining a Class and Creating an Object
  4. Defining Accessibility and Scope
  5. Passing Parameters to a Method
  6. Overloading Methods
  7. Using Constructors
  8. Static Class Members
  9. Namespaces and XML Commenting
  10. Aww Man... Not Homework

The Stack and the Heap

Stack Heap Diagram

If you're not already confused enough, this is sure to do it. Variables can be one of two types: a value type or a reference type. The two types relate to how an object is stored in memory. If you remember from Part 2, an integer occupies 4 bytes in memory, so the operating system knows exactly how much to allocate. But what about string? The size in memory will grow and shrink depending on how many characters are in the string.

Integers are known as value types. Value types store themselves, and the data they contain directly in the an area of memory called the stack. Strings are reference type variables. In the stack, a reference is created to another part of memory known as the heap which actually contains all the data for the string. All objects are stored on the heap.

This is important for two reasons. When you declare a value type variable, you must initialize it before it can be used and then you can assign it a value separately.

int myInt;  // this declares myInt
myInt = 42;        // this assigns a value to myInt 

When you declare a reference type variable, you must initialize it using the new keyword. Using new allocates some memory on the heap for your variable.

House myHouse = new House();

Later you'll learn that when you pass reference variables or try to copy them, special rules apply.

<< Previous

Next >>