Class Instance Constructors
- Instance constructors are used to create and initialize instances.
- A class can have more than one constructor.
- If the class does not have a constructor, a default parameterless constructor is automatically generated for you and the default values are used to initialize the object fields.
- The class constructor can invoke the constructor of the base class through the initializer.
Class Private Constructors
- It is commonly used in classes that contain static members only.
- If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.
- Private constructors are useful to prevent creation of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.
Class Static Constructors
- A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
- A static constructor does not take access modifiers or have parameters.
- A static constructor cannot be called directly.
- The user has no control on when the static constructor is executed in the program.
- A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
Structure Constructors
Struct constructors are similar to class constructors, except for the following differences:
- Structs cannot contain explicit parameterless constructors.
- Struct members are automatically initialized to their default values.
- A struct cannot have an initializer in the form: base (argument-list).
Destructors
- Destructors cannot be used with structs. They are only used with classes.
- A class can only have one destructor.
- Destructors cannot be inherited or overloaded.
- Destructors cannot be called. They are invoked automatically.
- A destructor does not take modifiers or have parameters.
- The destructor implicitly calls the Object.Finalize method on the object's base class. The Finalize method is called recursively for all of the instances in the inheritance chain, from the most derived to the least derived.
- The programmer has no control on when the destructor is called because this is determined by the garbage collector. The garbage collector checks for objects that are no longer being used by the application. It considers these objects eligible for destruction and reclaims their memory. Destructors are also called when the program exits.
No comments:
Post a Comment