![]() CATEGORIES: BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism |
Nbsp; All Types Are Derived from System.ObjectThe runtime requires every type to ultimately be derived from the System.Object type. This means that the following two type definitions are identical.
Because all types are ultimately derived from System.Object, you are guaranteed that every object of every type has a minimum set of methods. Specifically, the System.Object class offers the public instance methods listed in Table 4-1. In addition, types that derive from System.Object have access to the protected methods listed in Table 4-2. TABLE 4-1Public Methods of System.Object
TABLE 4-2Protected Methods of System.Object
The CLR requires all objects to be created using the new operator. The following line shows how to create an Employee object.
Employee e = new Employee("ConstructorParam1");
Here’s what the new operator does:
1.It calculates the number of bytes required by all instance fields defined in the type and all of its base types up to and including System.Object (which defines no instance fields of its own). Every object on the heap requires some additional members—called the type object pointer and the sync block index—used by the CLR to manage the object. The bytes for these additional members are added to the size of the object. 2.It allocates memory for the object by allocating the number of bytes required for the specified type from the managed heap; all of these bytes are then set to zero (0).
3.It initializes the object’s type object pointer and sync block index members. 4.The type’s instance constructor is called, passing it any arguments (the string "Constructor Param1" in the preceding example) specified in the call to new. Most compilers automatically emit code in a constructor to call a base class’s constructor. Each constructor is responsible for initializing the instance fields defined by the type whose constructor is being called. Eventu- ally, System.Object’s constructor is called, and this constructor method does nothing but return. After new has performed all of these operations, it returns a reference (or pointer) to the newly created object. In the preceding code example, this reference is saved in the variable e, which is of type Employee. By the way, the new operator has no complementary delete operator; that is, there is no way to explicitly free the memory allocated for an object. The CLR uses a garbage-collected environment (described in Chapter 21) that automatically detects when objects are no longer being used or ac- cessed and frees the object’s memory automatically.
Date: 2016-03-03; view: 724
|