Home > Articles > Programming > C#

This chapter is from the book

This chapter is from the book

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.

Note

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:

  1. Create a new Windows Application project titled Object Example.

  2. Change the form's Text property to Object Example using the Properties window.

  3. 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 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

  1. Double-click the button to access its Click event.

  2. Enter the first line of code as follows (remember to press Enter at the end of each statement):

  3. 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."

  4. Enter the second line of code exactly as shown here:

  5. 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.

  6. Enter the third line of code as shown next:

  7. objGraphics.Clear(System.Drawing.SystemColors.Control);

    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 parameter—the 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.

  8. Enter the following statement:

  9. 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:

    • 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 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.

  10. Last, you have to clean up after yourself by entering the following code statement:

  11. objGraphics.Dispose();

    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.

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 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020