- Understanding Objects
- Understanding Properties
- Understanding Methods
- Building a Simple Object Example Project
- Understanding Collections
- Using the Object Browser
- Summary
- Q&A
- Workshop
Building a Simple Object Example Project
The only way to really grasp what objects are and how they work is to use them.
You're about to create a sample project that uses objects. If you're new to programming with objects, you'll probably find this a bit confusing. However, I'll walk you through step by step, explaining each section in detail.
The project you're going to create consists of a single form with one button on it. When the button is clicked, a line will be drawn on the form beginning at the upper-left corner of the form and extending to the lower-right corner.
NOTE
In Hour 18, "Working with Graphics," you'll learn all about the drawing functionality within Visual C# .NET.
Creating the Interface for the Drawing Project
Follow these steps to create the interface for your project:
Create a new Windows Application project titled Object Example.
Change the form's Text property to Object Example using the Properties window.
Add a new button to the form and set its properties as shown in the following table:
Property |
Value |
Name |
btnDraw |
Location |
112,120 |
Text |
Draw |
Writing the Object-Based Code
You're now going to add code to the Click event of the new button. I'm going to explain each statement, and at the end of the steps, I'll show the complete code listing.
Object Example Project
Double-click the button to access its Click event.
Enter the first line of code as follows (remember to press Enter at the end of each statement):
System.Drawing.Graphics objGraphics = null;
Here you've just created a variable that will hold an instance of an object. Objects don't materialize out of thin air; they have to be created. When a form is loaded into memory, it loads all its controls (that is, creates the control objects), but not all objects are created automatically like this. The process of creating an instance of an object is called instantiation. When you load a form, you instantiate the form object, which in turn instantiates its control objects. You could load a second instance of the form, which in turn would instantiate a new instance of the form and new instances of all controls. You would then have two forms in memory and two of each controls used.
To instantiate an object in code, you create a variable that holds a reference to an instantiated object. You then manipulate the variable as an object. The statement you wrote in step 2 creates a new variable called objGraphics, which holds a reference to an object of type Graphics from the .NET Framework System.Drawing class. You also initialized the value for objGraphics to null. (You learn more about variables in Hour 11.)
Enter the second line of code exactly as shown here:
objGraphics = CreateGraphics();
CreateGraphics is a method of the form. Under the hood, the CreateGraphics method is pretty complicated, and I discuss it in detail in Hour 18. For now, understand that the method CreateGraphics instantiates a new object that represents the client area of the current form. The client area is the gray area within the borders and title bar of a form. Anything drawn onto the objGraphics object appears on the form. What you've done is set the variable objGraphics to point to an object that was returned by the CreateGraphics method. Notice how values returned by a property or method don't have to be traditional values such as numbers or text; they can also be objects.
Enter the third line of code as shown next:
objGraphics.Clear(System.Drawing.SystemColors.Control);
This statement clears the background of the form using whatever color the user has selected as the Windows Control color, which Windows uses to paint forms.
How does this happen? In step 3, you used the CreateGraphics method of the form to instantiate a new graphics object in the variable objGraphics. With the code statement you just entered, you're calling the Clear method of the objGraphics object. The Clear method is a method of all Graphics objects used to clear the graphics surface. The Clear method accepts a single parameter (a value passed to it from calling code)the color you want used to clear the surface.
The value you're passing to the parameter looks fairly convoluted. Remember that "dots" are a way of separating objects from their properties and methods (properties, methods, and events are often called object members). Knowing this, you can discern that System is an object (technically it's a Namespace, as discussed in Appendix A, "The 10,000-Foot View," but for our purposes it behaves just like an object) because it appears before any of the dots. However, there are multiple dots. What this means is that Drawing is an object property of the System object; it's a property that returns an object. So the dot following Drawing is used to access a member of the Drawing object, which in turn is a property of the System object. We're not done yet, however, because there is yet another dot. Again, this indicates that SystemColors, which follows a dot, is an object of the Drawing object, which in turn is...well, you get the idea. As you can see, object references can and do go pretty deep, and you'll use many dots throughout your code. The key points to remember are as follows:
-
Text that appears to the left of a dot is always an object (or Namespace).
-
Text that appears to the right of a dot is a property reference or a method call. If the text is followed by a set of parenthesis, it is a method call. If not, it's a property.
-
Methods can return objects, just as properties can. The only surefire way to know whether the text between two dots is a property or method is to look at the icon of the member in the IntelliSense drop-down or to consult the documentation of the object.
The final text in this statement is the word Control. Because Control isn't followed by a dot, you know that it's not an object; therefore, it must be a property or a method. Because you expect this string of object references to return a color value to be used to clear the Graphics object, you know that Control in this instance must be a property or a method that returns a value (because you need the return value to set the Clear() method). A quick check of the documentation (or simply realizing that the text isn't followed by a set of parentheses) would tell you that Control is indeed a property. The value of Control always equates to the color designated on the user's computer for the face of forms and buttons. By default, this is a light gray (often fondly referred to as battleship gray), but users can change this value on their computers. By using this property to specify a color rather than supplying the actual value for gray, you are assured that no matter what color scheme is used on a computer, the code will clear the form to the proper system color. System colors are explained in Hour 18.
Enter the following statement. Press Enter at the end of each lineVisual C# .NET will know that this is a single statement because of the location of the semicolon, which is always used to denote the end of a code statement:
objGraphics.DrawLine(System.Drawing.Pens.Blue, 0, 0, this.DisplayRectangle.Width, this.DisplayRectangle.Height);
This statement draws a blue line on the form. Within this statement are a single method call and three property references. Can you tell what's what? Immediately following objGraphics (and a dot) is DrawLine. Because no equal sign is present (and the text is followed by parentheses), you can deduce that this is a method call. As with the Clear() method, the parentheses after DrawLine() are used to enclose a value passed to the method. The DrawLine() method accepts the following parameters in the order in which they appear here:
A Pen
X value of first coordinate
Y value of first coordinate
X value of second coordinate
Y value of second coordinate
The DrawLine() method draws a straight line between coordinate one and coordinate two, using the pen specified in the Pen parameter. I'm not going to go into detail on pens here (refer to Hour 18), but suffice it to say that a pen has characteristics such as width and color. Looking at the dots once more, notice that you're passing the Blue property of the Pens object. Blue is an object property that returns a predefined Pen object that has a width of 1 pixel and the color blue.
You're passing 0 as the next two parameters. The coordinates used for drawing are defined such that 0,0 is always the upper-left corner of a surface. As you move to the right of the surface, X increases, and as you move down the surface, Y increases; you can use negative values to indicate coordinates that appear to the left or above the surface. The coordinate 0,0 causes the line to be drawn from the upper-left corner of the form's client area.
The object property DisplayRectangle is referenced twice in this statement. DisplayRectangle is a property of the form that holds information about the client area of the form. Here, you're simply getting the Width and Height properties of the client area and passing them to the DrawLine() method. The result is that the end of the line will be at the lower-right corner of the form's client area.
Last, you have to clean up after yourself by entering the following code statement:
objGraphics.Dispose();
Objects often make use of other objects and resources. The underlying mechanics of an object can be truly mind-boggling and are almost impossible to discuss in an entry-level programming book. The net effect, however, is that you must explicitly destroy most objects when you're done with them. If you don't destroy an object, it may persist in memory and it may hold references to other objects or resources that exist in memory. This means you can create a memory leak within your application that slowly (or rather quickly) munches system memory and resources. This is one of the cardinal no-no's of Windows programming, yet the nature of using resources and the fact you're responsible for telling your objects to clean up after themselves makes this easy to do. If your application causes memory leaks, your users won't call for a plumber, but they might reach for a monkey wrench...
Objects that must explicitly be told to clean up after themselves usually provide a Dispose method. When you're done with such an object, call Dispose on the object to make sure it frees any resources it might be holding.
For your convenience, following are all the lines of code:
System.Drawing.Graphics objGraphics = null; objGraphics = CreateGraphics(); objGraphics.Clear(System.Drawing.SystemColors.Control); objGraphics.DrawLine(System.Drawing.Pens.Blue, 0, 0, this.DisplayRectangle.Width, this.DisplayRectangle.Height); objGraphics.Dispose();
Testing Your Object Example Project
Now for the easy part: Run the project by pressing F5 or by clicking the Start button on the toolbar. Your form looks pretty much as it did at design time. Clicking the button causes a line to be drawn from the upper-left corner of the form's client area to the lower-right corner (see Figure 3.7).
NOTE
If you receive any errors when you attempt to run the project, go back and make sure the code you entered exactly matches the code I've provided.
Figure 3.7 Simple lines and complex drawings are accomplished using objects.
Resize the form, larger or smaller, and click the button again. Notice that the form is cleared and a new line is drawn. If you were to omit the statement that invokes the Clear method (and you're welcome to stop your project and do so), the new line would be drawn, but any and all lines already drawn would remain.
NOTE
If you use Alt+Tab to switch to another application after drawing one or more lines, the lines will be gone when you come back to your form. In fact, this will occur whenever you overlay the graphics with another form. In Hour 18, you'll learn why this is so and how to work around this behavior.
Stop the project now by clicking Stop Debugging on the Visual C# .NET toolbar, and then click Save All to save your project. What I hope you've gained from building this example is not necessarily that you can now draw a line (which is cool), but rather an understanding of how objects are used in programming. As with learning almost anything, repetition aids in understanding. Therefore, you'll be working with objects a lot throughout this book.