2.2 Defining Class Fields

 <  Day Day Up  >  

You want to add a field to your class.


Technique

Right-click on the class name within the Class View window (Ctrl+Shift+C). Select Add Field (Alt+P,L). In the Add Field dialog box, set the desired access level using Table 2.1 as a guide. Select the data type and name of your field. Additionally, if your field needs to be static or constant, select the appropriate field modifier radio button.

Comments

A field is simply a variable within your class that is available to store a value of a certain data type. In the past, a field has been traditionally called a variable , so we tend to interchange the two terms, but the semantics are still the same.

Fields are useful for internal state information about your object. One of the good programming practice rules to follow when designing a class is to use data encapsulation by never exposing internal class variables with a public access modifier. Take care when designing your class and specifically adding fields to make sure you never allow external clients who are using your class to modify a member variable. Later in this chapter, you'll see different ways you can allow clients to change member variables without giving them access to the variable itself, thereby allowing you to first validate that the data they want to send is valid and will not disrupt the current state of your object.

A field can be any data type. You might have noticed that when you created the field using the Add Field dialog, the data type drop-down list contained the C# built-in value types. This list does not contain any of your project's user -defined value types or any other classes. If you need to use a data type not listed in the drop-down list, you have to change the wizard-generated code after you create the field or simply write out the whole declaration yourself to save time.

When creating a field, you can choose to add an access modifier. The static access modifier designates that a member variable belongs to the type itself rather than a specific instance of an object. If the value of a static variable is changed, it changes for every instance of the class currently in existence. Nonstatic member fields within a specific instance are simply copies of the type's member fields, whereas a static field is shared across all instances of that type.

A const modifier denotes that a field is constant throughout the lifetime of that instance. It cannot be modified. Furthermore, you must define a constant using a value type so that it can be evaluated at compile time. The only exception to this rule is that you can use a string object as a constant.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

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