Designing C# Objects Using Classes
You learned about what makes an object an object in Hour 3, "Understanding Objects and Collections." Since that hour, you've learned how to manipulate objects such as forms and controls. The real power of leveraging objects comes from being able to design and implement custom objects of your own design. In this hour, you'll learn how to create your own objects by using classes (in contrast to using static methods). You'll learn how to define the template for an object and how to create your own custom properties and methods.
The highlights of this hour include the following:
-
Encapsulating data and code using classes
-
Comparing instance member classes with static member classes
-
Constructors and destructors
-
Creating an object interface
-
Exposing object attributes as properties
-
Exposing methods
-
Instantiating objects from classes
-
Binding an object reference to a variable
-
Understanding object lifetime
-
Releasing object references
NOTE
There is simply no way to become an expert on programming classes in a single hour. However, when you've finished with this hour, you'll have a working knowledge of creating classes and deriving custom objects from those classes; consider this hour a primer on object-oriented programming. I strongly encourage you to seek other texts that focus on object-oriented programming after you feel comfortable with the material presented throughout this book.
Understanding Classes
Classes enable you to develop applications using object-oriented programming (OOP) techniques (recall that I discussed OOP briefly in Hour 3). Classes are templates that define objects. Although you may not have known it, you have been programming with classes throughout this book. When you create a new form in a C# project, you are actually creating a class that defines a form; forms instantiated at runtime are derived from the class. Using objects derived from predefined classes, such as a C# Form class, is just the start of enjoying the benefits of object-oriented programmingto truly realize the benefits of OOP, you must create your own classes.
The philosophy of programming with classes is considerably different from that of "traditional" programming. Proper class-programming techniques can make your programs better, both in structure and in reliability. Class programming forces you to consider the logistics of your code and data more thoroughly, causing you to create more reusable and extensible object-based code.
Encapsulating Data and Code Using Classes
An object derived from a class is an encapsulation of data and code; that is, the object comprises its code and all the data it uses. For example, suppose that you need to keep track of employees in an organization and that you need to store many of pieces of information for each employee, such as Name, Date Hired, and Title. In addition, suppose you need methods for adding and removing employees, and you want all this information and functionality available to many functions within your application. You could use static methods to manipulate the data. However, this would most likely require many variable arrays, as well as code to manage the arrays.
A better approach is to encapsulate all the employee data and functionality (adding and deleting routines and so forth) into a single, reusable object. Encapsulation is the process of integrating data and code into one entityan object. Your application, as well as external applications, could then work with the employee data through a consistent interfacethe Employee object's interface (An interface is a set of exposed functionalityessentially, code routines.)
NOTE
Creating objects for use outside of your application is beyond the scope of this book. The techniques you'll learn in this hour, however, are directly applicable to creating externally creatable objects.
The encapsulation of data and code is the key detail of classes. By encapsulating the data and the routines to manipulate the data into a single object by way of a class, you free application code that needs to manipulate the data from the intricacies of data maintenance. For example, suppose company policy has changed so that when a new employee is added to the system, a special tax record needs to be generated and a form needs to be printed. If the data and code routines weren't encapsulated in a common object but were written in various places throughout your code, you would need to modify each and every module that contained code to create a new employee record. By using a class to create an object, you need to change only the code in one location: within the object. As long as you don't modify the interface of the object (discussed shortly), all the routines that use the object to create a new employee will instantly have the policy change in effect.
Comparing Instance Members with Static Members
You learned in Hour 11, "Creating and Calling Methods," that C# does not support global methods, but supports only class methods. By creating static methods, you create methods that can be accessed from anywhere in the project through the class.
Instance methods are similar to static methods in how they appear in the C# design environment and in the way in which you write code within them. However, the behavior of classes at runtime differs greatly from that of static members. With static members, all static data is shared by all members of the class. In addition, there are never multiple instances of the static class data. With instance member classes, objects are instantiated from a class and each object receives its own set of data. Static methods are accessed through the class, whereas nonstatic methods (also called instance methods) are accessed through instances of the class.
Instance methods differ from static methods in more ways than just in how their data behaves. When you define a static method, it is instantly available to other classes within your application. However, instant member classes aren't immediately available in code. Classes are templates for objects. At runtime, your code doesn't interact with the code in the class per se, but it instantiates objects derived from the class. Each object acts as its own class "module" and thus it has its own set of data. When classes are exposed externally to other applications, the application containing the class's code is called the server. Applications that create and use instances of objects are called clients. When you use instances of classes in the application that contains those classes, the application itself acts as both a client and a server. In this hour, I'll refer to the code instantiating an object derived from a class as client code.
Begin by creating a new Windows Application titled Class Programming Example. Change the name of the default form to fclsClassExample and set its Text property to Class Example. Next, change the entry point of the project in the method Main() to reference fclsClassExample instead of Form1. Add a new class to the project by choosing Add Class from the Project menu. Save the class with the name clsMyClass.cs (see Figure 17.1).
Figure 17.1 Classes are added to a project the same as other object files are added.
Constructors and Destructors
As you open your new class file, you'll notice that C# added the public class declaration and a method called clsMyClass(). This is known as the class constructor. A constructor has the same name as the class, includes no return type, and has no return value. A class constructor is called whenever a class object is instantiated. Therefore, it's normally used for initialization if some code needs to be executed automatically when a class is instantiated. If a constructor isn't specified in your class definition, the Common Language Runtime (CLR) will provide a default constructor.
NOTE
Objects consume system resources. The .NET Framework (discussed in Hour 24, "The 10,000-Foot View") has a built-in mechanism to free resources used by objects. This mechanism is called the Garbage Collector (and it is discussed in Hour 24 as well). Essentially, the garbage collector determines when an object is no longer being used and then destroys the object. When the garbage collector destroys an object, it calls the object's destructor method. If you aren't careful about how to implement a destructor method, you can cause problems. I recommend that you seek a book dedicated to object-oriented programming to learn more about constructors and destructors.
Creating an Object Interface
For an object to be created from a class, the class must expose an interface. As I mentioned earlier, an interface is a set of exposed functionality (essentially, code routines/methods). Interfaces are the means by which client code communicates with the object derived from the class. Some classes expose a limited interface, whereas some expose complex interfaces. The content and quantity of your class's interface is entirely up to you.
The interface of a class consists of one or more of the following members:
Properties
Methods
Events
For example, assume that you are creating an Employee object (that is, a class used to derive employee objects). You must first decide how you want client code to interact with your object. You'll want to consider both the data contained within the object and the functions the object can perform. You might want client code to be able to retrieve the name of an employee and other information such as sex, age, and the date of hire. For client code to get these values from the object, the object must expose an interface member for each of the items. Recall from Hour 3 that values exposed by an object are called properties. Therefore, each piece of data discussed here would have to be exposed as a property of the Employee object.
In addition to properties, you can expose functionssuch as a Delete or AddNew function. These functions may be simple in nature or very complex. The Delete function of the Employee object, for example, might be quite complex. It would need to perform all the actions necessary to delete an employee, including such things as removing the employee from an assigned department, notifying accounting to remove the employee from the payroll, notifying security to revoke the employee's security access, and so on. Publicly exposed functions of an object, as you should remember from Hour 3, are called methods.
Properties and methods are the most commonly used interface members. Although designing properties and methods may be new to you, by now using them isn't; you've been using properties and methods in almost every hour so far. Here, you're going to learn the techniques for creating properties and methods for your own objects.
For even more interaction between the client and the object, you can expose custom events. Custom object events are similar to the events of a form or a text box. However, with custom events you have complete control over the following:
The name of the event
The parameters passed to the event
When the event occurs
NOTE
Events in C# are based on delegates. Creating custom events is complicated, and I'll be covering only custom properties and methods in this hour.
Properties, methods, and events together make up an object's interface. This interface acts as a contract between the client application and the object. Any and all communication between the client and the object must transpire through this interface (see Figure 17.2).
Figure 17.2 Clients interact with an object via the object's interface.
The technical details of the interaction between the client and the object by way of the interface are, mercifully, handled by C#. Your responsibility is to define the properties, methods, and events of an object so that its interface is logical, consistent, and exposes all the functionality a client needs to use the object.
Exposing Object Attributes as Properties
Properties are the attributes of objects. Properties can be read-only, or they can allow both reading and writing of their values. For example, you may want to let a client retrieve the value of a property containing the path of the component, but not let the client change it because you can't change the path of a running component.
You can add properties to a class in two ways. The first is to declare public variables. Any variable declared as public instantly becomes a property of the class (technically, it's referred to as a field). For example, suppose you have the following statement in the Declarations section of a class:
public long Quantity;
Clients could read from and write to the property using code such as the following:
objMyObject.Quantity = 139;
This works, but significant limitations exist that make this approach less than desirable:
You can't execute code when a property value changes. For example, what if you wanted to write the quantity change to a database? Because the client application can access the variable directly, you have no way of knowing when the value of the variable changes.
You can't prevent client code from changing a property, because the client code accesses the variable directly.
Perhaps the biggest problem is this: How do you control data validation? For instance, how could you ensure that Quantity was never set to a negative value?
You simply can't work around these issues using a public variable. Instead of exposing public variables, you should create class properties using property procedures.
Property procedures enable you to execute code when a property is changed, to validate property values, and to dictate whether a property is read-only, write-only, or both readable and writable. Declaring a property procedure is similar to declaring a method, but with some important differences. The basic structure of a property looks like this:
Private int privatevalue; public int propertyname { get { return privatevalue; // Code to return the property's value . } set { privatevalue = value; // Code that accepts a new value. } }
The first word in the property declaration simply designates the scope of the property (public or private). Properties declared with public are available to code outside of the class (they can be accessed by client code). Properties declared as private are available only to code within the class. Immediately following public or private are the data type and property name.
Place your cursor after the left bracket following the statement public class clsMyclass and press Enter to create a new line. Type the following statements into your class:
private int m_intHeight; public int Height { get { } set { } }
You might be wondering why you just created a module-level variable of the same name as your property procedure (with a naming prefix, of course). After all, I just finished preaching about the problems of using a module-level variable as a property. A property has to get its value from somewhere, and a module-level variable is usually the best place to store it. The property procedure will act as a wrapper for this variable. Notice here that the variable is private rather than public. This means that no code outside of the class can view or modify the contents of this variable; as far as client code is concerned, this variable doesn't exist.
Between the property declaration statement and its closing brace are two constructs: the get construct and a set construct. Each of these constructs is discussed in its own section.
Creating Readable Properties Using the get Accessor
The get accessor is used to place code that returns a value for the property when read by the client. If you remove the get accessor and its corresponding brackets, clients won't be able to read the value of the property. It's rare that you'll want to create such a property, but you can.
Think of the get accessor as a method; whatever you return as the result of the method becomes the property value. Add the following statement between the get brackets:
return m_intHeight;
You return the value of the property by using the return keyword followed by the value.
Creating Writable Properties Using the set Accessor
The set accessor is where you place code that accepts a new property value from client code. If you remove the set accessor (and its corresponding brackets), clients won't be able to change the value of the property. Leaving the get accessor and removing the set accessor creates a read-only property; clients can retrieve the value of the property but they cannot change it.
Add the following statement between the set brackets:
m_intHeight = value;
The set clause uses a special variable called value, which is provided automatically by C# and always contains the value being passed to the property by the client code. The statement you just entered assigns the new value to the module-level variable.
As you can see, the property method is a wrapper around the module-level variable. When the client code sets the property, the set accessor stores the new value in the variable. When the client retrieves the value of the property, the get accessor returns the value in the module-level variable.
So far, the property code, with its get and set accessor, doesn't do anything different from what it would do if you were to simply declare a public variable (only the property procedure requires much more code). However, look at this variation of the same set accessor:
set { if (value >=10) m_intHeight = value; }
This set accessor restricts the client to setting the Height property to a value greater than 10. If a value less than 10 is passed to the property, the property procedure is exited without setting m_intHeight. You're not limited to performing only data validation; you can pretty much add whatever code you desire and even call other methods. Go ahead and add the verification statement to your code so that the set accessor looks like this one. Your code should now look like the procedure shown in Figure 17.3.
Figure 17.3 This is a property procedure, complete with data validation.
Exposing Functions as Methods
Unlike a property that acts as an object attribute, methods are functions exposed by an object. A method can return a value, but it doesn't have to. Create the following method in your class now. Enter this code on the line following the closing bracket for the declared public int Height property:
public long AddTwoNumbers(int intNumber1, int intNumber2) { return intNumber1 + intNumber2; }
Recall that methods defined with a data-type return values, whereas methods defined with void don't. To make a method private to the class and therefore invisible to client code, declare the method as private rather than public.