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

Defining a Class and Creating an Object

Let's start with an example that a lot of people would face in real life. We'll create a system to manage our clients accounts. Let's dive right in by defining our class.

// All classes start with the keyword, class, followed by the name (in our case Client)
class Client
{
        // Properties to store important information
        public string name;           // stores the name of our client
        public uint accountNumber;    // stores their account number
        public decimal balance;               // shows how much they owe us
 
        // Down here we would create methods and stuff
}

So we have a simple version of our Client class. For right now we're going to ignore the methods and just focus on how we would create an object from this class. If you notice, we added public to the front of our properties. This allows us to access them directly from the object we create. Take a look:

// first we create a new customer, this is always in the form of:
//   = new 
Client firstClient = new Client();
 
// this sets the value of name
firstClient.name = "Mr. T";
 
// we can create another client without affecting the first
Client nextClient = new Client();
nextClient.name = "Mr. Pink";
 
Console.WriteLine(firstClient.name); // outputs Mr. T 
      
      

So now we have two clients and our business is booming.

<< Previous

Next >>