- 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.
Every project you've built so far uses objects, but you're now going to create a sample project that specifically illustrates using 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.
You're going to modify your Picture Viewer project to include a button that, when clicked, draws a colored border around the picture.
Creating the Interface for the Drawing Project
Continuing on with the Picture Viewer project you've been using in this chapter, add a new button to the form and set its properties as shown in the following table:
Property |
Value |
Name |
btnDrawBorder |
Location |
301, 69 |
Size |
85, 23 |
Text |
Draw Border |
Writing the Object-Based Code
You're now going to add code to the Click event of the button. I'm going to explain each statement, and at the end of the steps, I'll show the complete code listing.
- Double-click the Draw Border button to access its Click event.
- Enter the first line of code as follows (remember to press Enter at the end of each statement):
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 used control.
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 variable declaration statement you wrote in step 2 creates a new variable called objGraphics, which holds a reference to an object of type Graphics (the type comes first, then the variable name). You learn more about variables in Hour 18.
Next, enter the second line of code exactly as shown here:
objGraphics = this.CreateGraphics();
CreateGraphics() is a method of the form (remember, the keyword this is shorthand for referencing the current 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 will appear 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 could also be objects.
Enter the third line of code as shown next:
objGraphics.Clear(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? After declaring the objGraphics object, 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 graphic surface. The Clear() method accepts a single parameter: the color you want used to clear the surface.
The value you're passing to the parameter might seem a bit odd. 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 SystemColors is an object because it appears before any of the dots. Object references can and do go pretty deep, and you'll use many dots throughout your code. The key points to remember are
- 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 method call. If the text is followed by a set of parentheses (), it's a method call. If not, it's most likely a property.
- Methods can return objects, just as properties can. The only surefire ways 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 method. Because you expect this string of object references to return a color value to be used to clear the graphic 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 would tell you that Control is indeed a property, but you don't even need to do that because there are no parenthesis at the end of Control, so it can't be a method and therefore has to be 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're assured that no matter the color scheme 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. Note: Press Enter after each line. Remember, Visual C# uses a semicolon to denote the end of a statement, so it will consider all three lines as being one code statement.
objGraphics.DrawRectangle(Pens.Blue, picShowPicture.Left - 1, picShowPicture.Top - 1, picShowPicture.Width + 1, picShowPicture.Height + 1);
This statement draws a blue rectangle around the picture on the form. Within this statement is a single method call and five property references. Can you tell what's what? Immediately following objGraphics (and a dot) is DrawRectangle. Because no equal sign is present, you can deduce that this is a method call. As with the Clear() method, the parentheses after DrawRectangle are used to enclose values passed to the method.
The DrawRectangle() method accepts the following parameters in the order in which they appear here:
- A pen
- X value of the upper-left corner
- Y value of the upper-left corner
- Width of the rectangle
- Height of the rectangle
The DrawRectangle() method draws a prefect rectangle using the X, Y, Width, and Height values passed to it. The attributes of the line (color, width, and so on) are determined by the pen specified in the Pen parameter. I'm not going to go into detail on pens here (see Hour 18). 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.
For the next two parameters, you're passing property values. Specifically, you're passing the top and left values for the picture, less one. If you passed the exact left and top values, the rectangle would be drawn on the form at exactly the top and left properties of the PictureBox, and you wouldn't see them because controls by default overlap any drawing performed on the form.
The last two property references are for the Height and Width of the PictureBox. Again, we adjust the values by one to ensure that the rectangle is drawn outside the borders of the PictureBox.
Finally, you have to clean up after yourself by entering the following code statement:
objGraphics.Dispose();
Objects often use 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 finished with them. If you don't destroy an object, it might persist in memory, and it might hold references to other objects or resources that exist in memory. This means that 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 finished with such an object, call Dispose() on the object to make sure that it frees any resources it might be holding.
For your convenience, here are all the lines of code:
Graphics objGraphics = null; objGraphics = this.CreateGraphics(); objGraphics.Clear(SystemColors.Control); objGraphics.DrawRectangle(Pens.Blue, picShowPicture.Left - 1, picShowPicture.Top - 1, picShowPicture.Width + 1, picShowPicture.Height + 1); objGraphics.Dispose();
Click Save All on the toolbar to save your work before continuing.
Testing Your Object Example Project
Now the easy part: Run the project by pressing F5 or by clicking the Start button on the toolbar. Your form looks pretty much like it did at design time. Clicking the button causes a blue rectangle to be drawn around the PictureBox (see Figure 3.7).
Figure 3.7 Simple lines and complex drawings are accomplished using objects.
Stop the project now by clicking Stop Debugging on the Visual C# toolbar. What I hope you've gained from building this example is not necessarily that you can now draw a rectangle (which is cool), but rather an understanding of how objects are used in programming. As with learning almost anything, repetition aids in understanding. That said, you'll be working with objects a lot throughout this book.