Sunday, December 5, 2010

Implementing Constructors in C #:

A 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.

Types of 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 member of the class.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Calc
{
class Calculator
{
private int number1, number2, total;
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();
Console.ReadLine();
}

}
}

Note: - 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 case, the instantiation of an object of this class invokes the default constructor.

No comments:

Recent Posts