Instance Variables and Properties

In Chapter 3, we declared all of an application's variables in the application's Main method. Variables declared in the body of a particular method are known as local variables and can be used only in that method. When a method terminates, the values of its local variables are lost. Recall from Section 4.2 that an object has attributes that are carried with the object as it is used in an application. Such attributes exist before a method is called on an object and after the method completes execution.

Attributes are represented as variables in a class declaration. Such variables are called fields and are declared inside a class declaration but outside the bodies of the class's method declarations. When each object of a class maintains its own copy of an attribute, the field that represents the attribute is also known as an instance variableeach object (instance) of the class has a separate instance of the variable in memory. [Note: In Chapter 9, Classes and Objects: A Deeper Look, we discuss another type of field called a static variable, where all objects of the same class share one copy of the variable.]

A class normally consists of one or more properties that manipulate the attributes that belong to a particular object of the class. The example in this section demonstrates a GradeBook class that contains a courseName instance variable to represent a particular GradeBook object's course name, and a CourseName property to manipulate courseName.

GradeBook Class with an Instance Variable and a Property

In our next application (Figs. 4.74.8), class GradeBook (Fig. 4.7) maintains the course name as an instance variable so that it can be used or modified at any time during an application's execution. The class also contains one methodDisplayMessage (lines 2430)and one propertyCourseName (line 1121). Recall from Chapter 2 that properties are used to manipulate an object's attributes. For example, in that chapter, we used a Label's Text property to specify the text to display on the Label. In this example, we use a property in code rather than in the Properties window of the IDE. To do this, we first declare a property as a member of the GradeBook class. As you will soon see, the GradeBook's CourseName property can be used to store a course name in a GradeBook (in instance variable courseName) or retrieve the GradeBook's course name (from instance variable courseName). Method DisplayMessagewhich now specifies no parametersstill displays a welcome message that includes the course name. However, the method now uses the CourseName property to obtain the course name from instance variable courseName.

Figure 4.7. GradeBook class that contains a private instance variable, courseName and a public property to get and set its value.

(This item is displayed on page 139 in the print version)

 1 // Fig. 4.7: GradeBook.cs
 2 // GradeBook class that contains a courseName instance variable,
 3 // and a property to get and set its value.
 4 using System;
 5
 6 public class GradeBook
 7 {
 8 private string courseName; // course name for this GradeBook
 9
10 // property to get and set the course name
11 public string CourseName 
12 { 
13  get 
14  { 
15  return courseName; 
16  } // end get 
17  set 
18  { 
19  courseName = value; 
20  } // end set 
21 } // end property CourseName 
22
23 // display a welcome message to the GradeBook user
24 public void DisplayMessage()
25 {
26 // use property CourseName to get the
27 // name of the course that this GradeBook represents
28 Console.WriteLine( "Welcome to the grade book for
{0}!",
29 CourseName ); // display property CourseName
30 } // end method DisplayMessage
31 } // end class GradeBook

Figure 4.8. Create and manipulate a GradeBook object.

(This item is displayed on page 143 in the print version)

 1 // Fig. 4.8: GradeBookTest.cs
 2 // Create and manipulate a GradeBook object.
 3 using System;
 4
 5 public class GradeBookTest
 6 {
 7 // Main method begins program execution
 8 public static void Main( string[] args )
 9 {
10 // create a GradeBook object and assign it to myGradeBook
11 GradeBook myGradeBook = new GradeBook();
12
13 // display initial value of CourseName
14 Console.WriteLine( "Initial course name is: '{0}'
",
15 myGradeBook.CourseName );
16
17 // prompt for and read course name
18 Console.WriteLine( "Please enter the course name:" );
19 string theName = Console.ReadLine(); // read a line of text
20 myGradeBook.CourseName = theName; // set name using a property
21 Console.WriteLine(); // output a blank line
22
23 // display welcome message after specifying course name
24 myGradeBook.DisplayMessage();
25 } // end Main
26 } // end class GradeBookTest
 
Initial course name is: ''

Please enter the course name:
CS101 Introduction to C# Programming

Welcome to the grade book for
CS101 Introduction to C# Programming!

A typical instructor teaches more than one course, each with its own course name. Line 8 declares courseName as a variable of type string. Line 8 is a declaration for an instance variable because the variable is declared in the body of the class (lines 731) but outside the bodies of the class's method (lines 2430) and property (lines 1121). Every instance (i.e., object) of class GradeBook contains one copy of each instance variable. For example, if there are two GradeBook objects, each object has its own copy of courseName (one per object). All the methods and properties of class GradeBook can directly manipulate its instance variable courseName, but it is considered good practice for methods of a class to use that class's properties to manipulate instance variables (as we do in line 29 of method DisplayMessage). The software engineering reasons for this will soon become clear.

Access Modifiers public and private

Most instance variable declarations are preceded with the keyword private (as in line 8). Like public, keyword private is an access modifier. Variables or methods declared with access modifier private are accessible only to methods of the class in which they are declared. Thus, variable courseName can be used only in property CourseName and method DisplayMessage of class GradeBook.

Software Engineering Observation 4 2

Precede every field and method declaration with an access modifier. As a rule of thumb, instance variables should be declared private and methods and properties should be declared public. If the access modifier is omitted before a member of a class, the member is implicitly declared private by default. (We will see that it is appropriate to declare certain methods private, if they will be accessed only by other methods of the class.)

Good Programming Practice 4 1

We prefer to list the fields of a class first, so that, as you read the code, you see the names and types of the variables before you see them used in the methods of the class. It is possible to list the class's fields anywhere in the class outside its method declarations, but scattering them can make code difficult to read.

Good Programming Practice 4 2

Placing a blank line between method and property declarations enhances application readability.

Declaring instance variables with access modifier private is known as information hiding. When an application creates (instantiates) an object of class GradeBook, variable courseName is encapsulated (hidden) in the object and can be accessed only by methods and properties of the object's class. In class GradeBook, the property CourseName manipulates the instance variable courseName.

Setting and Getting the Values of private Instance Variables

How can we allow a program to manipulate a class's private instance variables but ensure that they remain in a valid state? We need to provide controlled ways for programmers to "get" (i.e., retrieve) the value in an instance variable and "set" (i.e., modify) the value in an instance variable. For these purposes, programmers using languages other than C# normally use methods known as get and set methods. These methods typically are made public, and provide ways for the client to access or modify private data. Historically, these methods begin with the words "Get" and "Set"in our class GradeBook, for example, if we were to use such methods they might be called GetCourseName and SetCourseName, respectively.

Although you can define methods like GetCourseName and SetCourseName, C# properties provide a more elegant solution. Next, we show how to declare and use properties.

GradeBook Class with a Property

The GradeBook class's CourseName property declaration is located in lines 1121 of Fig. 4.7. The property begins in line 11 with an access modifier (in this case, public), followed by the type that the property represents (string) and the property's name (CourseName). Property names are normally capitalized.

Properties contain accessors that handle the details of returning and modifying data. A property declaration can contain a get accessor, a set accessor or both. The get accessor (lines 1316) enables a client to read the value of private instance variable courseName; the set accessor (lines 1720) enables a client to modify courseName.

After defining a property, you can use it like a variable in your code. For example, you can assign a value to a property using the = (assignment) operator. This executes the code in the property's set accessor to set the value of the corresponding instance variable. Similarly, referencing the property to use its value (for example, to display it on the screen) executes the code in the property's get accessor to obtain the corresponding instance variable's value. We show how to use properties shortly. By convention, we name each property with the capitalized name of the instance variable that it manipulates (e.g., CourseName is the property that represents instance variable courseName)C# is case sensitive, so these are distinct identifiers.

get and set Accessors

Let us look more closely at property CourseName's get and set accessors (Fig. 4.7). The get accessor (lines 1316) begins with the identifier get and is delimited by braces. The accessor's body contains a return statement, which consists of the keyword return followed by an expression. The expression's value is returned to the client code that uses the property. In this example, the value of courseName is returned when the property CourseName is referenced. For example, the following statement

string theCourseName = gradeBook.CourseName;

where gradeBook is an object of class GradeBook, executes property CourseName's get accessor, which returns the value of instance variable courseName. That value is then stored in variable theCourseName. Note that property CourseName can be used as simply as if it were an instance variable. The property notation allows the client to think of the property as the underlying data. Again, the client cannot directly manipulate instance variable courseName because it is private.

The set accessor (lines 1720) begins with the identifier set and is delimited by braces. When the property CourseName appears in an assignment statement, as in

gradeBook.CourseName = "CS100 Introduction to Computers";

the text "CS100 Introduction to Computers" is passed to an implicit parameter named value, and the set accessor executes. Notice that value is implicitly declared and initialized in the set accessorit is a compilation error to declare a local variable value in this body. Line 19 stores this value in instance variable courseName. Note that set accessors do not return any data when they complete their tasks.

The statements inside the property in lines 15 and 19 (Fig. 4.7) each access courseName even though it was declared outside the property. We can use instance variable courseName in the methods and properties of class GradeBook because courseName is an instance variable of the class. The order in which methods and properties are declared in a class does not determine when they are called at execution time, so you can declare method DisplayMessage (which uses property CourseName) before you declare property CourseName. Within the property itself, the get and set accessors can appear in any order, and either accessor can be omitted. In Chapter 9, we discuss how to omit either a set or get accessor to create so-called "read-only" and "write-only" properties, respectively.

Using Property CourseName in Method DisplayMessage

Method DisplayMessage (lines 2430 of Fig. 4.7) does not receive any parameters. Lines 2829 output a welcome message that includes the value of instance variable courseName. We do not reference courseName directly. Instead, we access property CourseName (line 29), which executes the property's get accessor, returning the value of courseName.

GradeBookTest Class That Demonstrates Class GradeBook

Class GradeBookTest (Fig. 4.8) creates a GradeBook object and demonstrates property CourseName. Line 11 creates a GradeBook object and assigns it to local variable myGradeBook of type GradeBook. Lines 1415 display the initial course name using the object's CourseName propertythis executes the property's get accessor, which returns the value of courseName.

Note that the first line of the output shows an empty name (marked by ''). Unlike local variables, which are not automatically initialized, every field has a default initial valuea value provided by C# when you do not specify the initial value. Thus, fields are not required to be explicitly initialized before they are used in an applicationunless they must be initialized to values other than their default values. The default value for an instance variable of type string (like courseName) is null. When you display a string variable that contains the value null, no text is displayed on the screen. We will discuss the significance of null in Section 4.8.

Line 18 prompts the user to enter a course name. Local string variable theName (declared in line 19) is initialized with the course name entered by the user, which is returned by the call to ReadLine. Line 20 assigns theName to object myGradeBook's CourseName property. When a value is assigned to CourseName, the value specified (in this case, theName) is assigned to implicit parameter value of CourseName's set accessor (lines 1720, Fig. 4.7). Then parameter value is assigned by the set accessor to instance variable courseName (line 19 of Fig. 4.7). Line 21 (Fig. 4.8) displays a blank line, then line 24 calls myGradeBook's DisplayMessage method to display the welcome message containing the course name.

Preface

Index

    Introduction to Computers, the Internet and Visual C#

    Introduction to the Visual C# 2005 Express Edition IDE

    Introduction to C# Applications

    Introduction to Classes and Objects

    Control Statements: Part 1

    Control Statements: Part 2

    Methods: A Deeper Look

    Arrays

    Classes and Objects: A Deeper Look

    Object-Oriented Programming: Inheritance

    Polymorphism, Interfaces & Operator Overloading

    Exception Handling

    Graphical User Interface Concepts: Part 1

    Graphical User Interface Concepts: Part 2

    Multithreading

    Strings, Characters and Regular Expressions

    Graphics and Multimedia

    Files and Streams

    Extensible Markup Language (XML)

    Database, SQL and ADO.NET

    ASP.NET 2.0, Web Forms and Web Controls

    Web Services

    Networking: Streams-Based Sockets and Datagrams

    Searching and Sorting

    Data Structures

    Generics

    Collections

    Appendix A. Operator Precedence Chart

    Appendix B. Number Systems

    Appendix C. Using the Visual Studio 2005 Debugger

    Appendix D. ASCII Character Set

    Appendix E. Unicode®

    Appendix F. Introduction to XHTML: Part 1

    Appendix G. Introduction to XHTML: Part 2

    Appendix H. HTML/XHTML Special Characters

    Appendix I. HTML/XHTML Colors

    Appendix J. ATM Case Study Code

    Appendix K. UML 2: Additional Diagram Types

    Appendix L. Simple Types

    Index



    Visual C# How to Program
    Visual C# 2005 How to Program (2nd Edition)
    ISBN: 0131525239
    EAN: 2147483647
    Year: 2004
    Pages: 600

    Similar book on Amazon

    Flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net