Class Construction and Destruction
If you declare a variable of a class in your program, when the program comes up, the compiler reserves enough memory space for each member of the class…
Constructors Fundamentals#
Method Initializer#
If you declare a variable of a class in your program, when the program comes up, the compiler reserves enough memory space for each member of the class. The memory space reserved for each member variable is filled with an initial value based on its type. For a string object, the space would be left empty. For an integer type, the space would be filled with 0. A better way to take care of this type is to provide a value whose role is to initialize the member variables with the values of your choice. A method that initializes an object can return any value but it is preferable to be of type void because its primary purpose is to reset the values. Since this method would give a starting value to all member variables that need to be initialized, it should have an equivalent argument for each of the member variables that it would initialize. The method initializer does not have to initialize all members of the class. For example, the previous execution of the program shows that the member variables that are of type string are initialized with empty strings. In such a case, you may not have to initialize such variables. To implement a method initializer, simply assign its argument to the corresponding member variable of the class. Here are examples:
public class Flower
{
public int Type;
public int Color;
public char Arrangement;
public double UnitPrice;
public void Initializer(int tp, int clr, char arng, double price)
{
Type = tp;
Color = clr;
Arrangement = arng;
UnitPrice = price;
}
}Once you have instantiated the class, you can invoke a method initializer to set its starting values. Below is an illustration of this process:
public class Flower
{
public int Type;
public int Color;
public char Arrangement;
public double UnitPrice;
public void Initializer(int tp, int clr, char arng, double price)
{
Type = tp;
Color = clr;
Arrangement = arng;
UnitPrice = price;
}
}Using a method initializer, after initializing the object, you can use the values it holds as you see fit. Practical Learning: Introducing Constructors
- Start Microsoft Visual Web Developer
- To create a new web site, on the main menu, click File -> New Web Site...
- Make sure the Language is set to Visual C#. Click the second box to the right of Location, delete the suggested name of the web site and replace it with geometry7
- Click OK
- In the Solution Explorer, right-click Default.aspx and click Rename
- Type index.aspx and press Enter
- In the Solution Explorer, right-click geometry7 and click Add New Item...
- In the Templates list, click Class
- Replace the suggested name with Cylinder
- Click Add
- Read the message box that comes up and click Yes
- Change the class as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for Cylinder /// </summary> public class Cylinder { public double rad; public double hgt; public double Volume() { return this.rad * this.rad * this.hgt * 3.14159; } }
- Click the index.aspx tab
- To access the method, change the code as follows: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Geometry: Cylinder</title> </head> <body> <% var Cup = new Cylinder(); Cup.rad = 22.08; Cup.hgt = 28.14; Response.Write("=-=Cylinder Characteristics=-="); Response.Write("<br>Radius: "); Response.Write(Cup.rad); Response.Write("<br>Height: "); Response.Write(Cup.hgt); Response.Write("<br>Volume: "); Response.Write(Cup.Volume()); %> </body> </html>
- Press Ctrl + F5 to see the result
- Return to your programming environment
Default Constructor#
A constructor is a special method that is created when the object comes to life. This particular method holds the same name as the class and it initializes the object whenever that object is created. When you create a class, if you don't declare a constructor, the compiler creates one for you; this is useful because it lets all other objects of the program know that the object exists. This compiler-created constructor is called the default constructor. If you want, you can create your own constructor. To create a constructor, declare a method that holds the same name as the class. Remember that the method must not return any value. Here is an example:
public class Flower
{
Flower()
{
}
}Declaring an instance of a class automatically triggers the creation of an object constructor, regardless of whether you end up using that specific object. Upon declaration, the default constructor is invoked by the system.
The Constructor Initializer#
A constructor can be used to initialize the member variables of a class. As such, a constructor provides a valuable alternative to a method initializer, the type of method we saw earlier. To use a constructor to initialize the member variables of a class, provide as arguments the necessary variables that you intend to initialize. You don't have to initialize all member variables in the constructor, only those that need to be initialized. In fact, you should initialize only those members that you think the other objects would need when using this object. This means that your object may have fields that, either the external objects don't need to modify (or access) or the member variable(s) will be initialized later when called from the needed object(s). To implement a default constructor, you can just initialize the desired members of the class. For a member variable of a numeric type, you can just assign the desired constant to each. If the variable is a character, assign a single-quoted symbol to it. If the variable is a string, then assign a double-quoted value to the variable. Here are examples:
public class Flower
{
public int Type;
public int Color;
public char Arrangement;
public decimal UnitPrice;
public Flower()
{
Type = 1;
Color = 1;
Arrangement = 'V';
UnitPrice = 0M;
}
}
}Constructor Overloading#
A class's default constructor is typically where initial values are assigned to its members. In C#, you're not limited to just the default; you can define multiple constructors as needed for your application. This capability means constructors can be overloaded by varying their parameter lists. For instance, a simple constructor might accept only one argument to initialize a specific field, while setting other fields to their default states. Here is an example:
public class Flower
{
public int Type;
public int Color;
public char Arrangement;
public decimal UnitPrice;
public Flower()
{
Type = 1;
Color = 1;
Arrangement = 'V';
UnitPrice = 0M;
}
public Flower(int tp)
{
Type = tp;
Color = 1;
Arrangement = 'V';
UnitPrice = 0M;
}
}If you create a class with only one constructor as in the current example, when declaring an instance of the class, you must use that constructor: you cannot use the default constructor that doesn't take an argument. When declaring the variable, initialize it with a constructor with parentheses and provide the value(s) in the parentheses of the constructor. Here is an example:
public class Flower
{
public string Type;
public string Color;
public string Arrangement;
public double UnitPrice;
public Flower()
{
Type = "";
Color = "Red";
Arrangement = "Basket";
UnitPrice = 35.95D;
}
public Flower(string tp)
{
Type = tp;
Color = "Red";
Arrangement = "Basket";
UnitPrice = 35.95D;
}
}In the same way, you can create different constructors for different initializations, although it would not be realistic to create a different constructor for each variable. If you create different constructors with different arguments to initialize (remember the rules of method overloading), when declaring the classes, make sure you initialize each instance with the right number of arguments; otherwise, the compiler would complain. If you create a class with only one constructor and that constructor has at least one argument, the default constructor would not be available anymore. If you want to access a default constructor of an object, you have two alternatives:
- If you don't create any constructor at all on a class, the default constructor would always be available whenever you invoke that class
- If you create at least one constructor on a class and supply at least one argument to that constructor, you must explicitly create a default constructor for your class.
Practical Learning: Overloading a Constructor
- Click the Cylinder.cs tab and change it as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for Cylinder /// </summary> public class Cylinder { public double rad; public double hgt; public double Volume() { return this.rad * this.rad * this.hgt * 3.14159; } public Cylinder() { this.rad = 0.00; this.hgt = 0.00; } public Cylinder(double radius, double height) { this.rad = radius; this.hgt = height; } }
- Click the index.aspx tab
- To access the method, change the code as follows: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Geometry: Cylinder</title> </head> <body> <% // Using the default construcor var Cup = new Cylinder(); Cup.rad = 22.08; Cup.hgt = 28.14; Response.Write("=-=Cylinder Characteristics=-="); Response.Write("<br>Radius: "); Response.Write(Cup.rad); Response.Write("<br>Height: "); Response.Write(Cup.hgt); Response.Write("<br>Volume: "); Response.Write(Cup.Volume()); Response.Write("<p></p>"); // Using the constructor that takes two arguments Cup = new Cylinder(45.66, 36.38); Response.Write("=-=Cylinder Characteristics=-="); Response.Write("<br>Radius: "); Response.Write(Cup.rad); Response.Write("<br>Height: "); Response.Write(Cup.hgt); Response.Write("<br>Volume: "); Response.Write(Cup.Volume()); %> </body> </html>
- Press Ctrl + F5 to see the result
- Return to your programming environment
The Destructor of a Class#
As opposed to a constructor, a destructor is called when a program has finished using an object. A destructor does the cleaning behind the scenes. Like the default constructor, the compiler always creates a default destructor if you don't create one. Unlike the constructor, the destructor cannot be overloaded. This means that, if you decide to create a destructor, you can have only one. Like the default constructor, a destructor also has the same name as its class. This time, the name of the destructor starts with a tilde "~". To create a destructor, type ~ followed by the name of the class. Here is an example:
public class Flower
{
public string Type;
public string Color;
public string Arrangement;
public decimal UnitPrice;
public Flower()
{
Type = "";
Color = "Red";
Arrangement = "Basket";
UnitPrice = 35.95M;
}
public Flower(string tp)
{
Type = tp;
Color = "Red";
Arrangement = "Basket";
UnitPrice = 35.95M;
}
~Flower()
{
}
}Previous Copyright © 2009 C# Key Next

