Creating and Using Objects


A class is only a type definiton. To do something useful with it, one must create objects from the definition. Each object can maintain its own state; every object from the class exhibits the same behavior.

To create an object and use it:

  1. Declare a variable of the type of object you wish to use. If your class is called ToDoItem, your variable type will most likely be ToDoItem as well.

  2. Use the new operator to create an instance of the class. Set the variable equal to new , a space, the name of the class you wish to instantiate and parentheses.

  3. Type a semicolon.

  4. Invoke a function in the object or use a field by using the variable name, followed by a dot, followed by the member's name ( Figure 2.48 ).

    Figure 2.48 You create objects based on a class by using the new operator and assigning the result to a variable. Then you can use the variable to set fields or call functions.
     private void btnTask_Click(object sender,                      System.EventArgs e) {  ToDoItem item = new ToDoItem();   item.SetInfo(txtItem.Text,   txtDescription.Text);  } 

graphics/tick.gif Tips

  • You don't have to put the new instruction in the same line as the variable declaration. It is possible to declare the variable first in one line, then later in the program set the variable equal to a new object ( Figure 2.49 ).

    Figure 2.49 You don't have to declare the variable and create the object in the same statement. The declaration and instantiation can be separated.
     protected void Application_Start(Object sender,                                EventArgs e) {  ToDoList todo;   todo = new ToDoList();  } 
  • You can't invoke a function or set a field through a variable that has not been set to an object. The value of the variable before it has been set equal to a new instance of a class is null . Null is a reserved language keyword that means that a reference variable hasn't been set to an object ( Figure 2.50 ).

    Figure 2.50 You can't call a method or set a field through a null variable; the program gives you an error.
     class Person {    void Talk()    {    } } class App {    void DoTask1()    {      //*** error ***      //can't call method without      //creating instance  Person p1;   p1.Talk();  } } 
  • The variable type doesn't have to be the same type as the class you're creating. You can also choose a type that is a base class to the class you're creating. (See the "Inheriting a Class from Another" section in Chapter 5, "Class Inheritance.")




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