Monday, December 21, 2009

Constructors

Constructor is a method in a classs which is automatically invoked as soon as object is created.In C#.Net it is invoked by class name.

Syntax:
Classname referencename;
Reference = new classname();
Example:
Account a;
a=new Account();


Constructor may be of default type.copy type or parameterized.

Default Constructor:No parameters will be sent to this constrcutor .Intially the properties of the class are assigned default values(0's).
The syntax of the default constructor is as shown above.

Copy Constructor:This constructor create a clone of another object.

Syntax with example:
public Account(Account a)
{
this.Id=a.Id;
this.Name=a.Name;
this.Balance=a.Balance;
}


Constructor with parameters:This typeof constructors takes the values to the members of the class.

Syntax with example:
public Account(string n ,balance b,int i)
{

this.Id = i;
this.Name = n;
this.Balance = b;
}


Example:
Class:
Public Account
{
private int Id;
private string Name;
private decimal Balance;
//Default Constructor
Public Account()
{
Id =101;
Name="E101";
Balance=101.11;
}
//Constructor with parameter
Public Account(int Id,string Name,decimal Balance)
{
this.Id = id;
this.Name = name;
this.Balance = balance;
}
//Copy Constructor
Public Account(Account a)
{
this.Id=a.Id;
this.Name=a.Name;
this.Balance=a.Balance;
}
Public void Display()
{
Console.WriteLine("Id="+id.ToString());
Console.WriteLine("Name="+Name);
Console.WriteLine("Balance="+Balance.ToString());
}
}
Public static void(string []args)
{
//Accessing Default Constructor
Account a=new Account();
//Accessing Constructor with parameter
Account a1=new Account(1,"E1",11);
a1.Display();
//Accessing Copy Constructor
Account a2=new Account(2,"E2",22);
Account a2=new Account(a2);//Passing parameter as object
}


//Note:If all constructors are used together in program,then it is called Constructor overloading.

No comments:

Post a Comment