A constructor is a special type of method that is invoked when you create a new instance of a class.. Instance Constructors An instance constructor is called whenever an instance of a c
Trang 1Constructors and
Constructors and destructors perform special
functions as members of classes Constructors are
used to initialize objects Conversely, you can use
destructors to delete an object when it is not
required
This chapter introduces the concept of constructors
and destructors In addition, the chapter explains
how to implement constructors and destructors The chapter also explains how constructors and
destructors help in identifying the life cycle of the
object
In this chapter, you will learn to:
Implement constructors
Implement destructors
Identify the life cycle of an object
Objectives
Trang 3A constructor is a special type of method that is invoked when you create a new instance
of a class A constructor is used to initialize the members of the class The name of a constructor is the same as the name of the class that contains it
A constructor is complementary to a destructor It is good programming practice to use both constructors and destructors
To initialize member variables, a function can be invoked as soon as an object is created The following program is an example of writing an initialization function:
using System;
namespace Calc
{
{
static int number1, number2, total;
{
}
{
total = number1 + number2;
}
{
Console.WriteLine ("The Total is :{0}", total); }
public static void Main(string[] args) {
Calculator c1 = new Calculator ();
}
}
}
In the preceding example, the object of the class has to call the
Implementing Constructors
The Need of Constructors
Trang 4OOPs offers you a solution to overcome the preceding problem related to ensuring for invoking the initialize function While designing a class, you can include a special
member function within the class This member function is executed whenever an object
of the class is created Such functions are called constructors
There are two types of constructors, instance constructors and static constructors.
Instance Constructors
An instance constructor is called whenever an instance of a class is created These
constructors are used to initialize data members of the class For automatic initialization, the Calculator class can be rewritten by using a constructor For example, consider the following code:
using System;
namespace Calc
{
class Calculator
{
static int number1, number2, total;
// Constructors have same name as the class
Calculator()
{
number1 = 10;
number2 = 20;
}
public void AddNumber()
{
total = number1 + number2;
}
public void DisplayNumber()
{
Console.WriteLine ("The Total is :{0}", total);
}
public static void Main(string[] args)
{
Calculator c1 = new Calculator ();
c1.AddNumber ();
c1.DisplayNumber ();
}
}
}
Types of Constructors
Trang 5Note
Note
In the preceding code notice that there is no return type specified to the
Calculator()constructor This is because constructors do not return values The variable number1 is assigned with value 10 and number2 is assigned with value 20 when the constructor is invoked by the Common Language Runtime (CLR)
If there are no constructors defined for a class, the compiler creates a default constructor
In such a case, the instantiation of an object of this class invokes the default constructor
Static Constructors
Static constructors are used to initialize the static variables of a class These variables are created using the static keyword and they store values that can be shared by all the
instances of a class These constructors have an implicit private access The constructors will be invoked only once during the execution of a program
The following example illustrates the implementation of the static constructor:
public class Class1
{
static int number1;
int number2;
static Class1()
{
number1 = 10; //OK Since Number1 is a static variable in
number2 = 3; //Error Since Number2 is a non-static variable
in class1 }
}
In actual practice, constructors are used to initialize data members and not for any
input or output operations
We can have more than one constructor in a class Chapter 7 discusses this topic in
detail
Trang 6Objects can be initialized using the default constructor with values hard-coded in the program But there might be a requirement where the variables need to be initialized with user supplied values To tackle this problem, a constructor can be modified to accept the user supplied values at runtime
The following code illustrates the use of parameters in constructors:
using System;
namespace Calc
{
class Calculator
{
static int number1, number2, total;
//Constructor defined with two integer parameters num1 and num2
Calculator(int num1, int num2)
{
number1 = num1;
number2 = num2;
}
public void AddNumber()
{
total = number1 + number2;
}
public void DisplayNumber()
{
Console.WriteLine("The Total is :{0}", total);
}
public static void Main(string[] args)
{
int var1, var2;
Console.WriteLine("Enter Value 1 :");
var1=Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Enter Value 2 :");
var2 = Convert.ToInt16(Console.ReadLine());
Calculator C1 = new Calculator(var1,var2);
C1.AddNumber();
C1.DisplayNumber();
Console.ReadLine();
}
}
}
In the preceding code, the initialization values are passed to the member variables at the time of creating the object after accepting values from the user Therefore, the following statement:
Calculator C1 = new Calculator(var1,var2);
Constructors with Parameters
Trang 7Note
invokes the constructor function and passes the initialization values supplied by the user
at runtime, to the variables num1 and num2, respectively
In the preceding example, if you try to execute the statement,
Calculator c1=new Calculator();
it would generate an error “No overload for method ‘Calculator’ takes ‘0’ argument”
Trang 8Destructors are special methods that are used to release the instance of a class from
memory A class can have only one destructor The purpose of the destructor is to perform the required memory cleanup action The programmer has no control on when to call the destructor The NET Framework automatically runs the destructor to destroy objects in the memory
A destructor has the same name as its class but is prefixed with a ~, which is the symbol
of tilde Destructors cannot be inherited or overloaded The following code modifies the declaration of the Calculator class by using a destructor:
/* This code shows the use of destructor in the Calculator class */ using System;
namespace Destructors
{
class Calculator
{
static int number1, number2, total;
public void AddNumber()
{
total=number1+number2;
Console.WriteLine("The Result is {0}", total);
}
Calculator () //Constructor
{
number1=20;
number2=30;
total=0;
Console.WriteLine ("Constructor Invoked");
}
~Calculator () //Destructor
{
Console.WriteLine ("Destructor Invoked ");
}
static void Main(string[] args)
{
Calculator c1=new Calculator ();
c1.AddNumber();
}
}
}
Implementing Destructors
Declaration of Destructors
Trang 9Note
In the preceding code, the NET Framework automatically runs the destructor to destroy objects in the memory and displays the message “Destructor Invoked”
To see the output of the preceding program, press Ctrl+F5
The output of the preceding code is as follows
Output of the Calculator Class Program
Even when you do not call the destructor, garbage collector releases memory
Garbage Collection
Garbage collection is a process that automatically frees the memory of objects that are no
more in use The decision to invoke the destructor is made by a special program of C# known as the garbage collector However, an object loses scope at the end of the Main () method, the destructor is not necessarily invoked Therefore, in C#, you cannot determine
Trang 10Note
In C#, you cannot destroy an object explicitly in code In fact, it has the feature of garbage collection, which destroys the objects for the programmers The process of garbage collection happens automatically It ensures that:
reference of another object
C# provides special methods that are used to release the instance of a class from memory, Finalize() and Dispose()
The Finalize() destructor is a special method that is called from the class to which it belongs or from the derived classes The Finalize() destructor is called after the last reference to an object is released from the memory The NET Framework automatically runs the Finalize() destructor to destroy objects in the memory However, it is
important to remember that the Finalize() destructor may not execute immediately when an object loses scope This is because the Common Language Runtime (CLR) calls the Finalize() destructor using a system called reference-tracing garbage collection In reference-tracing garbage collection, the CLR periodically checks for objects that are not used by the application When such an object is found, the Finalize() destructor is called automatically and the garbage collector of the CLR releases the object from the memory
The Dispose() method is called to release a resource, such as a database connection, as soon as the object using such a resource is no longer in use Unlike the Finalize()
destructor, the Dispose() method is not called automatically, and you must explicitly call
it from a client application when an object is no longer needed The IDisposable
interface contains the Dispose() method Therefore, to call the Dispose() method, the class must implement the IDisposable interface
An interface defines properties, methods, and events Interface would be discussed in detail in Chapter 8
Trang 11Note
The following code shows the life cycle of an object of the TestCalculator class: using System;
//Life Cycle of an Object
namespace Objects
{
class TestCalculator
{
TestCalculator()
{
Console.WriteLine("Constructor Invoked");
}
~TestCalculator()
{
Console.WriteLine("Destructor Invoked");
}
public static void Main(string[] args)
{
Console.WriteLine("Main() Begins");
TestCalculator calc1 = new TestCalculator();
{
Console.WriteLine("Inner Block Begins ");
TestCalculator calc2 = new TestCalculator();
Console.WriteLine("Inner Block Ends");
}
Console.WriteLine("Main() ends");
}
}
}
To see the output of the preceding program, press Ctrl+F5
Identifying the Life Cycle of an Object
Trang 12The output of the preceding code is as follows
Output of the Life Cycle of Objects
The explanation of the preceding output is as follows:
Thecalc1 object has function scope Therefore, its constructor is executed after the execution of Main () begins
The calc2 object has block scope Therefore, its constructor is executed after the execution of the inner block begins
The destructor of all objects is invoked when garbage collector is invoked
Trang 13Just a minute:
Consider the following code snippet:
Class Number {
static mynumber;
public void NumDisplay() {
} static void Main(string[] args) {
number n1=new number();
n1.NumDisplay();
Console.ReadLine();
} }
The Number class has only one, static member variable called mynumber Which
constructor would you use to initialize mynumber ?
Answer:
Static constructor
Trang 141 Which of the following statement is true about garbage collection?
a In garbage collection the objects are not destroyed
b In garbage collection the objects are destroyed every time
c In garbage collection only unreferenced objects are destroyed
2 A destructor has the same name as its class but is prefixed with
3 _ process identifies the unused objects and releases them in C#
4 Consider the following code and identify which line will generate an error on
compilation:
using System;
//Life Cycle of an Object
namespace Objects
{
class Draw
{
public void Shape()
{
Console.WriteLine("in shape method");
}
public Draw() // line 1
{
Console.WriteLine("This is a constructor");
}
public static void main(string[] arg)
{
Draw obj = new Draw();
obj.Draw(); // line 3
obj.Shape(); // line 4
}
}
}
Consider the preceding code and answer the following question Which line in the code will generate an error on compilation?
a line 1
b line 2
c line 3
d line 4
5 TheIDisposable interface contains the method
Practice Questions
Trang 15In this chapter, you learned that:
Constructors are member functions of a class and are invoked when an instance of the class to which they belong is created
A constructor has the same name as its class
A destructor is invoked when any instance of a class ceases to exist
A destructor has the same name as its class, but it is prefixed with a ~ (tilde)
Constructors are special methods that allow control over the initialization of objects
Destructors are special methods that are used to release the instance of a class from memory
Garbage collection is a process that automatically frees the memory of objects that is
no more in use
The Finalize() destructor is called after the last reference to an object is released from the memory
TheDispose() method is called to release a resource, such as a database connection, when the object using such a resource is no longer in use
Summary
Trang 16Exercise 1
Predict the output of the following program:
using System;
namespace Square_Number
{
class CalculateSquare
{
int number;
public void Square(int number)
{
Console.WriteLine(number);
number *= number;
Console.WriteLine(number);
}
CalculateSquare()
{
number = 10;
Square(number);
}
static void Main(string[] args)
{
CalculateSquare cal = new CalculateSquare();
Console.ReadLine();
}
}
}
Exercise 2
Predict the output of the following program:
using System;
namespace CalculateNumber
{
class Calculate
{
static int number1;
public void Display(int number)
{
Console.WriteLine(number);
Exercises