Can someone please give me an overview of the use of constructors in .net.
I am currently trying to improve my oop and am a bit baffled by this subject.
Printable View
Can someone please give me an overview of the use of constructors in .net.
I am currently trying to improve my oop and am a bit baffled by this subject.
A constructor is just a method that initialises an instance. In C# a constructor has the same name as the class itself, e.g.Whenever you create an instance of a class using the "new" keyword you are implicitly calling a constructor, e.g.Code:public class SomeClass
{
// This is a constructor.
public SomeClass()
{
// Initialise the properties of the new instance here.
}
}
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();
if the SomeClass class has a constructor that takes those arguments, i.e.Code:SomeClass instance = new SomeClass(someString, someInteger);
Constructors can be overloaded, which allows you to create instances using different combinations of arguments, e.g. thisCode:public class SomeClass
{
// This is a constructor.
public SomeClass(string arg1, int arg2)
{
// Initialise the properties of the new instance here.
}
}
would allow you to do thisCode: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.
}
}
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.Code:SomeClass instance1 = new SomeClass();
SomeClass instance2 = new SomeClass(someString, someInteger);
Further reading: http://msdn2.microsoft.com/en-us/library/ace5hbzh.aspx
Thanks, that was concise and just what I was looking for.