Building an Object Example Project
The only way to really grasp what objects are and how they work is to use them. I've said this before but I can't say it enough: everything in C# is an object.
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.
In Hour 10, "Drawing and Printing," you'll learn all about the drawing functionality within C#.
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:
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.
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):
Enter the second line of code exactly as shown here:
Enter the third line of code as shown next:
System.Drawing.Graphics objGraphics = null;
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 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 12, "Using Constants, Data Types, Variables, and Arrays."
objGraphics = CreateGraphics();
CreateGraphics is a method of the form. The CreateGraphics method is pretty complicated under the hood, and I discuss it in detail in Hour 10. 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.
This statement clears the background of the form using whatever color the user has selected as the Windows forms color.
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 parameterthe color to which you want the surface cleared.
The value you're passing to the parameter looks fairly convoluted. Remember that "dots" are a method of separating objects from their properties and methods. Knowing this, you can discern that System is an object (technically it's a Namespace, as discussed in Hour 24, "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 the following:
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.
Methods are never objects. In addition, methods are always followed by parentheses. If the text in question isn't followed by parentheses, it's definitely a property. Therefore, text that appears between two dots is a property that returns an object. Such a property is called an object property.
The final text in this statement is the word Control. Because Control is not 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 must be a property or a method that returns a value. 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. 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 the color scheme used on a computer, the code will clear the form to the proper system color. System colors are explained in Hour 10.
Enter the following statement:
objGraphics.DrawLine(System.Drawing.Pens.Chartreuse, 0, 0, this.DisplayRectangle.Width, this.DisplayRectangle.Height);
This statement draws a chartreuse line on the form. Within this statement is 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:
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 10), 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 Chartreuse property of the Pens object. Chartreuse is an object property that returns a predefined Pen object that has a width of 1 pixel and the color chartreuse.
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:
Objects often make use of other objects and resources. The underlying mechanics of an object can be truly boggling and 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.
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.Chartreuse, 0, 0, this.DisplayRectangle.Width, this.DisplayRectangle.Height); objGraphics.Dispose();
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 line to be drawn from the upper-left corner of the form's client area to the lower-right corner see Figure 3.7.
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.
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 Hour 10, you'll learn why this is so and how to work around this behavior.
Stop the project now by clicking Stop Debugging on the C# 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.