Start C# here

Study C#.. Go ahead ! !

Monday, November 24, 2008

C# Constructor(s)

what are Constructors?

Constructors are methods that gets automatically invoked when an object of a class is created. Constructors are used to Initialize values to variables inside the class automatically at the time of object creation.
Constructors will be having the same name of the class itself. Constructor doesn't return any value.

Let's see an example for Constructor..

-------------------------------------
using System;

class HelloWorld
{
int iNum1,iNum2;
string sName,sAddress;

//Creating a Constructor
public HeloWorld() //Line1
{
iNum1=iNum2=0;
sName="";
sAddress="";
}
}
-------------------------------------

Here, in the above code we have created a default constructor with the name of the class. Constructors will not be having a return type.

The Line1 represents the constructor for the class HelloWorld. The same name of the class itself will be given to constructor also.

We can have multiple constructors inside a class but should be overloaded. We use overloaded constructors for initializing values by passing it to the object of the class.

Eg
-------------------------------------
using System;

class HelloWorld
{
int iNum1,iNum2;
string sName,sAddress;

//Creating a Constructor
public HeloWorld() //Line1
{
iNum1=iNum2=0;
sName="";
sAddress="";
}
//Overloaded constructor
public HelloWorld(int _iNum,string _sName,string _sAddress)
{
iNum1=_iNum; //Line1
sName=_sName;
sAddress=_sAddress;
iNum2=0;
}

}
-------------------------------------

Here, in the above code we have two constructors but our function signatures are different in both Constructors. In the first constructor the Function signature or parameter is void and in the second one we have three parameters one Integer and two strings. So for invoking the second constructor we must have to pass values to the object.

Eg
--------------------------
//Invokes the Default Constructor
HelloWorld hwObj=new HelloWorld();

//This invokes the Second constructor
HelloWorld hwObj1=new HelloWorld(20,"SMILU","TPRA");

--------------------------

Like this we can have many constructors inside a Class.

Now, if in the case we have Static class and variables and have to initialize those variables we need another type of constructors called Static constructors.
Static constructors are used for initializing values inside Static classes. We cannot have instance constructors inside the static classes.

For Creating a static constructor we can use the static keyword.
-----------------------------------------
static class HelloWorld
{
static int i;
static HelloWorld()
{
i=10;
}
}
------------------------------------------

These are the types of constructors in C#.

No comments: