Adding Fields to Classes


Fields serve as storage units. They are variable declarations within the class, outside of any functions.

To add a field to a class:

  • Inside a class definition, outside of functions, declare a variable (see Figure 2.66 ).

    Figure 2.66 Fields in classes can be of any type. In this code item and description are strings while list is of a type declared by Microsoft called System.Collections.Hashtable.
     class ToDoItem {  string item;   string description;  } class ToDoList {  Hashtable list;  } 

graphics/tick.gif Tips

  • By default all fields are private. This means that only code within the class can access the fields. If code outside of the class tries to access a private field, the compiler issues an error ( Figure 2.67 ).

    Figure 2.67 Fields are private by default. They can only be read or changed by other code inside the same class. You can change the scope of the field by adding public in front of the declaration.
     class Sibling {    //scope of _money is    //private to class  decimal _money;  public void PurchaseItems(decimal                             amount)    {      //PurchaseItems can change the      //value of _money  _money -= amount  ;    } } class App {    void BorrowMoney()    {      Sibling brother = new Sibling();      //this is illegal _money is private  brother._money -= 100  ;    } } 
  • You can change the access level for a field (from private to something else) using an access modifier (read "Exposing and Restricting Access to Members" in Chapter 5, "Class Inheritance," for details). For now, don't try to understand all the different scope rules, just realize that private means it can only be used inside the class, and public means it can be used everywhere.

  • Figure 2.66 shows a field in the ToDoList of type HashTable. HashTable is a class in System.Collections. It is used to maintain a list of objects, and to assign a key to each item. The ToDoList class will use the HashTable class to keep a list of ToDoItem objects.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

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