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
Using Constructors
Constructors are specials methods that are used whenever you first initialize an object. If you don't write a constructor, one is implicitly created, so it's better to create your own, so you can define how you want your objects initialized.
Constructors methods are defined by using the same name as the class in which it's a part of, and just like any other method, you can optionally pass parameters. Here's an example of both.
class Client { private string name; // If we don't pass a parameter this one is used and the client\s // name is set to Anonymous public Client() { name = "Anonymous"; } // If we pass a single string as a parameter, this is used // and the name is assigned the value of the string passed public Client(string newName) { name = newName; } }
I'm sure you noticed that we just overloaded the constructor. It works exactly the same as our methods. Here's how you would use the constructor to create an object.
Client client1 = new Client(); // client1's name is Anonymous Client client2 = new Client("Sho Nuff"); // client2's name is Sho Nuff
Pretty handy. The only problem I see with this is that we duplicated the "name = whatever;" logic in both constructors. Isn't it nice that there's a dandier way to go about this?
class Client { private string name; private decimal balance; // If we don't pass a parameter this one is used and the client's // name is set to Anonymous, and they'll have 0 dollars public Client() : this("Anonymous", 0.0) { // Operations to be performed after calling the // constructor that accepts two parameters } // If we pass a single string as a parameter, this is used // and the name is assigned the value of the string passed // and they'll have 0 dollars public Client(string newName) : this(newName, 0.0) { // Operations to be performed after calling the // constructor that accepts two parameters } // This one takes a string for the name and decimal for the // balance and assigns them both when the object is created public Client(string newName, decimal openingBalance) { name = newName; balance = openingBalance; } }