Wednesday, 12 March 2014

Constructor in C#

A constructor is a method that runs whenever an instance of a class is created.

public MyClass()
{

}

This is a simple constructor, any code you put inside it will run when an instance of the class is created. In order to be recognized as a constructor the method must have the same name as the class it belongs to.

Notice how the syntax differs from a normal method, there is no void or other return value type specified before the method name. This syntax is peculiar to constructors.

public MyClass()
{
IntProperty = 15;// This will set the IntProperty property to 15 whenever a new instance of the class is created.
}

Just like any other method,constructors can have arguments.

public MyClass(int StartingNumber)//This adds an argument to the constructor called StartingNumber
{
IntProperty = StartingNumber;//This sets the IntProperty property to the number provided in the argument.
}

This should look very similar to you, it is exactly the same as adding arguments to any other method.

protected void Page_Load(object sender, EventArgs e)
{
MyClass MyClassInstance = new MyClass(15);//This provides the number 15 as the constructor argument. 
}

This means that when the constructor runs it will set the value of IntProperty to 15.

No comments:

Post a Comment