A constructor is just a method that initialises an instance. In C# a constructor has the same name as the class itself, e.g.
Code:
public class SomeClass
{
// This is a constructor.
public SomeClass()
{
// Initialise the properties of the new instance here.
}
}
Whenever you create an instance of a class using the "new" keyword you are implicitly calling a constructor, e.g.
Code:
SomeClass instance = new SomeClass();
will call the constructor above. When you create an instance using the "new" keyword you can pass arguments if and only if there is a constructor with the same signature, e.g. you could only do this:
Code:
SomeClass instance = new SomeClass(someString, someInteger);
if the SomeClass class has a constructor that takes those arguments, i.e.
Code:
public class SomeClass
{
// This is a constructor.
public SomeClass(string arg1, int arg2)
{
// Initialise the properties of the new instance here.
}
}
Constructors can be overloaded, which allows you to create instances using different combinations of arguments, e.g. this
Code:
public class SomeClass
{
// This is a constructor.
public SomeClass()
{
// Initialise the properties of the new instance here.
}
// This is another constructor.
public SomeClass(string arg1, int arg2)
{
// Initialise the properties of the new instance here.
}
}
would allow you to do this
Code:
SomeClass instance1 = new SomeClass();
SomeClass instance2 = new SomeClass(someString, someInteger);
Note that constructors are used to initialise the new instance, i.e. set its properties. If there are no properties to set then you can leave the constructor body empty.
Further reading: http://msdn2.microsoft.com/en-us/library/ace5hbzh.aspx