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.
- Classes and Objects
- The Stack and the Heap
- Defining a Class and Creating an Object
- Defining Accessibility and Scope
- Passing Parameters to a Method
- Overloading Methods
- Using Constructors
- Static Class Members
- Namespaces and XML Commenting
- Aww Man... Not Homework
The Stack and the Heap
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.