User:Foxall/03

Ka Wiktionary

Hour 3. Understanding Objects and Collections[wax ka badal]

So far, you've gotten an introduction to programming in C# by building a Picture Viewer project. You spent the previous hour digging into the IDE and learning skills critical to your success with C#. In this hour, you're going to start learning about some important programming concepts, namely objects.

graphics/newterm.gif The term object, as it relates to programming, may have been new to you prior to this book. The more you work with C#, the more you'll hear about objects. C# is a true object-oriented language. This hour isn't going to discuss object-oriented programming in any detail, because object-oriented programming is a very complex subject and is well beyond the scope of this book. Instead, you'll learn about objects in a more general sense. Everything you use in C# is an object, so understanding this material is critical to your success with C#. Forms are objects, for example, as are the controls you place on a form. Pretty much every element of a C# project is an object and belongs to a collection of objects. All objects have attributes (called properties), most have methods, and many have events. Whether creating simple applications or building large-scale enterprise solutions, you must understand what an object is and how it works. In this hour, you'll learn what makes an object an object, and you'll learn about collections.

The highlights of this hour include the following:

  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch03lev1sec1.htm#ch03lev1sec1 Understanding objects]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch03lev1sec2.htm#ch03lev2sec1 Getting and setting properties]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch03lev1sec3.htm#ch03lev2sec3 Triggering methods]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch03lev1sec3.htm#ch03lev2sec4 Understanding method dynamism]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch03lev1sec4.htm#ch03lev2sec6 Writing object-based code]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch03lev1sec5.htm#ch03lev1sec5 Understanding collections]
  • [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch03lev1sec6.htm#ch03lev1sec6 Using the Object Browser]
graphics/bookpencil.gif If you've listened to the programming press at all, you've probably heard the term object oriented, and perhaps words such as polymorphism, encapsulation, and inheritance. In truth, these object-oriented features of C# are very exciting, but they're far beyond [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/03.htm#ch03 Hour 3]. You'll learn a little about object-oriented programming in this book, but if you're really interested in taking your programming skills to the next level, you should buy a book dedicated to the subject after you've completed this one.

Understanding Objects[wax ka badal]

Object-oriented programming has been a technical buzzword for quite some time. Almost everywhere you look�the Web, publications, books�you read about objects. What exactly is an object? Strictly speaking, it is a programming structure that encapsulates data and functionality as a single unit and for which the only public access is through the programming structure's interfaces (properties, methods, and events). In reality, the answer to this question can be somewhat ambiguous because there are so many types of objects�and the number grows almost daily. However, all objects share specific characteristics, such as properties and methods.

The most commonly used objects in Windows applications are the form object and the control object. Earlier hours introduced you to working with forms and controls and even showed you how to set form and control properties. In your Picture Viewer project from [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch01.htm#ch01 Hour 1], for instance, you added a picture box and two buttons to a form. Both the PictureBox and the Button control are control objects, but each is a specific type of control object. Another, less-technical example uses pets. Dogs and cats are definitely different entities (objects), but they both fit into the category of Pet objects. Similarly, text boxes and buttons are each a unique type of object, but they're both considered a control object. This small distinction is important.

Understanding Properties 

All objects have attributes used to specify and return the state of the object. These attributes are properties, and you've already used some of them in previous hours using the Properties window. Indeed, every object exposes a specific set of properties, but not every object exposes the same set of properties. To illustrate this point, I will continue with the Pet object concept. Suppose you have an object, and the object is a dog. This Dog object has a certain set of properties that are common to all dogs. These properties include attributes such as the dog's name, the color of its hair, and even the number of legs it has. All dogs have these same properties; however, different dogs have different values for these properties. [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/03.htm#ch03fig01 Figure 3.1] illustrates such a Dog object and its properties.

Figure 3.1. Properties are the attributes that describe an object.

graphics/03fig01.gof

 Getting and Setting Properties 

You've already seen how to read and change properties using the Properties window. The Properties window is available only at design time, however, and is used only for manipulating the properties of forms and controls. Most reading and changing of properties you'll perform will be done with C# code, not by using the Properties window. When referencing properties in code, you specify the name of the object first, followed by a period (.), and then the property name, as in the following syntax:

{ObjectName}.{Property}

If you had a Dog object named Bruno, for example, you would reference Bruno's hair color this way:

Bruno.HairColor

This line of code would return whatever value was contained in the HairColor property of the Dog object Bruno. To set a property to some value, you use an equal (=) sign. For example, to change the Dog object Bruno's Weight property, you would use a line of code such as the following:

Bruno.Weight = 90;
graphics/bookpencil.gif A little later in this hour, I discuss instantiation, which is the process of creating an object based on a template. It's important to note here that Bruno is a named instance of an object derived from a template or blueprint (called a class). Each object instance has its own set of data, such as property values. For example, you could also have a Dog object named Bonnie, which has a unique set of properties. In a more real-world example, consider how you can have two buttons on a form. Although they have different property values (such as Name), and they have different code within their Click events, they are both Button objects.

When you reference a property on the left side of an equal sign, you're setting the value. When you reference a property on the right side of the equal sign, you're getting (reading) the value.

Bruno.Weight = 90;

It's easier to see here that referencing the property on the left side of the equal sign indicates that you are setting the property to some value.

The following line of code places the value of the Weight property of the Dog object called Bruno into a temporary variable. This statement retrieves the value of the Weight property because the Weight property is referenced on the right side of the equal sign.

fltWeight = Bruno.Weight;

Variables are discussed in detail in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12.htm#ch12 Hour 12], "Using Constants, Data Types, Variables, and Arrays." For now, think of a variable as a storage location. When the processor executes this code statement, it retrieves the value in the Weight property of the Dog object Bruno and places it in the variable (storage location) titled Weight. Assuming that Bruno's Weight is 90, as set in the previous example, the computer would process the following code statement:

fltWeight = 90;

Just as in real life, some properties can be read but not changed. Suppose you had a Sex property to designate the gender of a Dog object. It's impossible for you to change a dog from a male to a female or vice versa (at least I think it is). Because the Sex property can be retrieved but not changed, it is a read-only property. You'll often encounter properties that can be set in Design view but become read-only when the program is running.

One example of a read-only property is the Height property of the Combo Box control. Although you can view the value of the Height property in the Properties window, you cannot change the value�no matter how hard you try. If you attempt to change the Height property using C# code, C# simply changes the value back to the default.

graphics/bookpencil.gif The best way to determine which properties of an object are read-only is to consult the online help for the object in question.
Working with an Object and Its Properties 

Now that you know what properties are and how they can be viewed and changed, you're going to experiment with properties in a simple project. In [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch01.htm#ch01 Hour 1], you learned how to set the Height and Width properties of a form using the Properties window. Now, you're going to change the same properties using C# code.

The project you're going to create consists of a form with some buttons on it. One button will enlarge the form when clicked, whereas the other will shrink the form. This is a very simple project, but it illustrates rather well how to change object properties in C# code.

  1. Start by creating a new Windows Application project (from the File menu, choose New, Project).
  2. Name the project Properties Example.
  3. Use the Properties window to change the name of the form to fclsShrinkMe. (Click the form once to select it and press F4 to display the Properties window.)
  4. Next, change the Text property of the form to Grow and Shrink.
  5. Click the View Code button in Solution Explorer to view the code behind the form. Scroll down and locate the reference to Form1 and change it to fclsShrinkMe.
  6. Click the Form1.cs [Design] tab to return to the form designer.

When the project first runs, the default form will have a Height and Width as specified in the Properties window. You're going to add buttons to the form that a user can click to enlarge or shrink the form at runtime.

Add a new button to the form by double-clicking the Button tool in the toolbox. Set the new button's properties as follows:

Property Set To
Name btnEnlarge
Location 111,70
Text Enlarge

Now for the Shrink button. Again, double-click the Button tool in the toolbox to create a new button on the form. Set this new button's properties as follows:

Property Set To
Name btnShrink
Location 111,120
Text Shrink

Your form should now look like the one shown in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/03.htm#ch03fig02 Figure 3.2].

Figure 3.2. Each button is an object, as is the form the buttons sit on.

graphics/03fig02.jpg

To complete the project, you need to add the small amount of C# code necessary to modify the form's Height and Width properties when the user clicks a button. Access the code for the Enlarge button now by double-clicking the Enlarge button. Type the following statement exactly as you see it here. Do not hit the Enter key or add a space after you've entered this text.

this.Width

When you typed the period, or "dot," as it's called, a small drop-down list appeared, like the one shown in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/03.htm#ch03fig03 Figure 3.3]. C# is smart enough to realize that this represents the current object (more on this in a moment), and to aid you in writing code for the object, it gives you a drop-down list containing all the properties and methods of the form. This feature is called IntelliSense, and it is relatively new to Visual Studio. Because C# is fully object-oriented, you'll come to rely on IntelliSense drop-down lists in a big way; I think I'd rather dig ditches than program without them.

Figure 3.3. IntelliSense drop- down lists, or auto-completion drop-down lists, make coding dramatically easier.

graphics/03fig03.jpg

Use the Backspace key to completely erase the code you just entered and enter the following code in its place (press Enter at the end of each line):

this.Width = this.Width + 20;
this.Height = this.Height + 20;

Again, the word this refers to the object to which the code belongs (in this case, the form). The word this is a reserved word; it's a word that you cannot use to name objects or variables because C# has a specific meaning for it. When writing code within a form module, as you are doing here, you should always use the this reserved word rather than using the name of the form. this is much shorter than using the full name of the current form, and it makes the code more portable (you can copy and paste the code into another form module and not have to change the form name to make the code work). Also, should you change the name of the form at any time in the future, you won't have to change references to the old name.

graphics/bookpencil.gif The word this is the equivalent to the Me reserved word in Visual Basic.

The code you've entered simply sets the Width and Height properties of the form to whatever the current value of the Width and Height properties happens to be, plus 20 pixels.

Redisplay the form designer by selecting the tab titled Form1.cs [Design]; then double-click the Shrink button to access its Click event and add the following code:

this.Width = this.Width � 20;
this.Height = this.Height � 20;

This code is very similar to the code in the Enlarge_Click event, except that it reduces the Width and Height properties of the form by 20 pixels.

Your screen should now look like [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/03.htm#ch03fig04 Figure 3.4].

Figure 3.4. The code you've entered should look exactly like this.

graphics/03fig04.jpg

graphics/bulb.gif As you create projects, it's a very good idea to save frequently. Save your project now by clicking the Save All button on the toolbar.

Again, display the form designer by clicking the tab Form1.cs [Design]. Your Properties Example is now ready to be run! Press F5 to put the project in Run mode (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/03.htm#ch03fig05 Figure 3.5]).

Figure 3.5. What you see is what you get�the form you created should look just as you designed it.

graphics/03fig05.jpg

Click the Enlarge button a few times and notice how the form gets bigger. Next, click the Shrink button to make the form smaller. When you've clicked enough to satisfy your curiosity (or until you get bored), end the running program and return to Design mode by clicking the Stop Debugging button on the toolbar.

Understanding Methods 

In addition to properties, most objects have methods. Methods are actions the object can perform, in contrast to attributes that describe the object. To understand this distinction, think about the Pet object example. A Dog object has a certain set of actions that it can perform. These actions, called methods in C#, include barking and tail wagging. [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/03.htm#ch03fig06 Figure 3.6] illustrates the Dog object and its methods.

Figure 3.6. Invoking a method causes the object to perform an action.

graphics/03fig06.gof

 Triggering Methods 

Think of methods as functions�which is exactly what they are. When you invoke a method, code is executed. You can pass data to the method, and methods may return values. However, a method is neither required to accept parameters (data passed by the calling code) nor required to return a value; many methods simply perform an action in code. Invoking (triggering) a method is similar to referencing the value of a property; you first reference the object's name, then a "dot," then the method name, followed by a set of parentheses, which can optionally contain any parameters that must be passed to the method.

{ObjectName}.{Method}();

For example, to make the hypothetical Dog object Bruno bark using C# code, you would use this line of code:

Bruno.Bark();
graphics/bookpencil.gif Method calls in C# must always have parentheses. Sometimes they'll be empty, but at other times they'll contain data.

Invoking methods is simple; the real skill lies in knowing what methods an object supports and when to use a particular method.

 Understanding Method Dynamism 

Properties and methods go hand in hand, and at times a particular method may become unavailable because of one or more property values. For example, if you were to set the NumberofLegs on the Dog object Bruno equal to zero, the Walk and Fetch methods would obviously be inapplicable. If you were to set the NumberofLegs property back to four, you could then trigger the Walk or Fetch methods again. In C#, a method or property won't physically become unavailable�you can still call it, but doing so might cause an exception (error) or the call may be ignored.

>

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.

graphics/bookpencil.gif In [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch10.htm#ch10 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):
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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch12.htm#ch12 Hour 12], "Using Constants, Data Types, Variables, and Arrays."

  1. Enter the second line of code exactly as shown here:
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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch10.htm#ch10 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.

  1. 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 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch24.htm#ch24 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch10.htm#ch10 Hour 10].

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

    • 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch10.htm#ch10 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.

  1. 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 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/03.htm#ch03fig07 Figure 3.7]).

Figure 3.7. Simple lines and complex drawings are accomplished using objects.

graphics/03fig07.jpg

graphics/bookpencil.gif 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.

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.

graphics/bookpencil.gif 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 [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch10.htm#ch10 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.

>

Understanding Collections

A collection is just what its name implies: a collection of objects. Collections make it easy to work with large numbers of similar objects by enabling you to create code that performs iterative processing on items within the collection. Iterative processing is an operation that uses a loop to perform actions on multiple objects, rather than writing the operative code for each object. In addition to containing an indexed set of objects, collections also have properties and may have methods. [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/03.htm#ch03fig08 Figure 3.8] illustrates the structure of a collection.

Figure 3.8. Collections contain sets of like objects, and they have their own properties and methods.

graphics/03fig08.gof

Continuing with the Dog/Pet object metaphor, think about what an Animals collection might look like. The Animals collection could contain one or more Pet objects, or it could be empty (containing no objects). All collections have a Count property that returns the total count of objects contained within the collection. Collections may also have methods, such as a Delete method used to remove objects from the collection or an Add method used to add a new object to the collection.

To better understand collections, you're going to create a small C# project that cycles through the Controls collection of a form, telling you the value of the Name property of every control on the form.

To create your sample project, follow these steps:

  1. Start C# now (if it's not already loaded) and create a new Windows Application project titled Collections Example.
  2. Change the text of the form to Collections Example by using the Properties window.
  3. Add a new button to the form by double-clicking the Button tool in the toolbox. Set the button's properties as follows:
Property Value
Name btnShowNames
Location 88,112
Size 120,23
Text Show Control Names
  1. Next, add some text box and label controls to the form. As you add the controls to the form, be sure to give each control a unique name. Feel free to use any name you like, but you can't use spaces in a control name. You may want to drag the controls to different locations on the form so that they don't overlap.
  2. When you are finished adding controls to your form, double-click the Show Control Names button to add code to its Click event. Enter the following code:
for (int intIndex=0; intIndex < this.Controls.Count; intIndex++)
{
 MessageBox.Show ("Control # " + intIndex.ToString() +
 " has the name " + this.Controls[intIndex].Name);
}
graphics/bookpencil.gif Every form has a Controls collection, which may or may not contain any controls. Even if no controls are on the form, the form still has a Controls collection.

The first statement (the one that begins with for) accomplishes a few tasks. First, it initializes the variable intIndex to 0, and then tests the variable. It also starts a loop executing the statement block (loops are discussed in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch15.htm#ch15 Hour 15], "Looping for Efficiency"), incrementing intIndex by one until intIndex equals the number of controls on the form, less one. The reason that intIndex must always be less than the Count property is that when referencing items in a collection, the first item is always item zero�collections are zero based. Thus, the first item is in location zero, the second item is in location one, and so forth. If you tried to reference an item of a collection in the location of the value of the Count property, an error would occur because you would be referencing an index that is one higher than the actual locations within the collection.

The MessageBox.Show() method (discussed in detail in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch18.htm#ch18 Hour 18], "Interacting with Users ") is a class available in the .NET Framework that is used to display a simple dialog box with text. The text that you are providing, which the MessageBox.Show() method will display, is a concatenation of multiple strings of text. (Concatenation is the process of adding strings together; it is discussed in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch13.htm#ch13 Hour 13], "Performing Arithmetic, String Manipulation, and Date/Time Adjustments.")

Run the project by pressing F5 or by clicking Start on the toolbar. Ignore the additional controls that you placed on the form and click the Show Control Names button. Your program will then display a message box similar to the one shown in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/03.htm#ch03fig09 Figure 3.9] for each control on your form (because of the loop). When the program is finished displaying the names of the controls, choose Stop Debugging from the Debug toolbar to stop the program, and then save the project.

Figure 3.9. The Controls collection enables you to get to each and every control on a form.

graphics/03fig09.jpg

Because everything in C# is an object, you can expect to use numerous collections as you create your programs. Collections are powerful, and the quicker you become comfortable using them, the more productive you'll become.

>

Using the Object Browser

C# includes a useful tool that lets you easily view members, such as properties and methods, of all the objects in a project: the Object Browser (see [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/03.htm#ch03fig10 Figure 3.10]). This is extremely useful when dealing with objects that aren't well documented, because it enables you to see all the members an object supports. To view the Object Browser, display the Other Windows submenu of the View menu and choose Object Browser.

Figure 3.10. The Object Browser lets you view all properties and methods of an object.

graphics/03fig10.jpg

The Browse drop-down list in the upper-left corner of the Object Browser is used to determine the browsing scope. You can choose Active Project to view only the objects referenced in the active project, or you can choose Selected Components (the default) to view a set of selected objects. The Object Browser shows a preselected set of objects for Selected Components, but you can customize the object set by clicking the Customize button next to the Browse drop-down list. I wouldn't recommend changing the custom object set until you have some experience using C# objects and some experience using the Object Browser, as well.

The top-level nodes in the Objects tree are libraries. Libraries are usually DLL or EXE files on your computer that contain one or more objects. To view the objects within a library, simply expand the library node. As you select objects within a library, the list to the right of the Objects tree will show information regarding the members of the selected object (refer to [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/03.htm#ch03fig10 Figure 3.10]). For even more detailed information, click a member in the list on the right, and the Object Browser will show information about the member in the gray area below the two lists.

Summary 

In this hour, you learned all about objects. You learned how objects have properties, which are attributes that describe the object. Some properties can be set at design time using the Properties window, and most can also be set at runtime in C# code. You learned that referencing a property on the left side of the equal sign has the effect of changing a property, whereas referencing a property on the right side of the equal sign retrieves the property's value.

In addition to properties, you learned that objects have executable functions, called methods. Like properties, methods are referenced by using a "dot" at the end of an object reference. An object may contain many methods and properties, and some properties can even be objects themselves. You learned how to "follow the dots" to interpret a lengthy object reference.

Objects are often used as a group, called a collection. You learned that a collection often contains properties and methods, and that collections let you easily iterate through a set of like objects. Finally, you learned that the Object Browser can be used to explore all the members of an object in a project.

The knowledge you've gained in this hour is fundamental to understanding programming with C#, because objects and collections are the basis on which applications are built. After you have a strong grasp of objects and collections�and you will have by the time you've completed all the hours in this book�you'll be well on your way to fully understanding the complexities of creating robust applications using C#.

Q&A
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/03.htm#qad1e12077 Q1:] Is there an easy way to get help about an object's member?
A1: Absolutely. C#'s context-sensitive Help extends to code as well as to visual objects. To get help on a member, write a code statement that includes the member (it doesn't have to be a complete statement), position the cursor within the member text, and press F1. For instance, to get help on the Count property of the controls collection, you could type this.Controls.Count, position the cursor within the word Count, and press F1.
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/03.htm#qad1e12096 Q2:] Are there any other types of object members besides properties and methods?
A2: Yes. An event is actually a member of an object, although it's not always thought of that way. Not all objects support events, however, but most objects do support properties and methods.

Workshop

The Workshop is designed to help you anticipate possible questions, review what you've learned, and get you thinking about how to put your knowledge into practice. The answers to the quiz are in [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01.htm#app01 Appendix A], "Answers to Quizzes/Exercises."

 Quiz
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec3.htm#ch03ans01 1:] True or False: C# is a true object-oriented language.
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec3.htm#ch03ans02 2:] An attribute that defines the state of an object is called a what?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec3.htm#ch03ans03 3:] To change the value of a property, the property must be referenced on which side of an equal sign?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec3.htm#ch03ans04 4:] What is the term for when a new object is created from a template?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec3.htm#ch03ans05 5:] An external function of an object (one that is available to code using an object) is called a what?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec3.htm#ch03ans06 6:] True or False: A property of an object can be another object.
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec3.htm#ch03ans07 7:] A group of like objects is called what?
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/app01lev1sec3.htm#ch03ans08 8:] What tool is used to explore the members of an object?
Exercises
  1. Create a new project and add text boxes and a button to the form. Write code that, when clicked, places the text in the first text box into the second text box. Hint: Use the Text property of the text box controls.
  2. Modify the collections example in this hour to print the Height of all controls, rather than the name.
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch03lev1sec8.htm Previous Section] [file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/ch04.htm Next Section]
[file:///C:/Documents%20and%20Settings/dani/Asztal/c%23in24h/03.htm#toppage Top]