I would add to the following types of constructors as follows
- Public : A constructor that is defined as public will be called whenever a class is instantiated. Also the instantiation of the class can be from anywhere and from any assemblies.
- Protected : A constructor is defined as protected in such cases where the base class will initialize on its own whenever derived types of it are created. In this case class object can only be created in the derived classes.
- Private : A constructor is defined as private in such cases whenever a class which contains only static members has to be accessed will avoid the creation of the object for the class. The object of the class cannot be created and is used when any single instance of the class is needed and we have a static property or method to get the instance of the class.
Constructor Overloading
C# supports overloading of constructors, which means, we can have constructors with different sets of parameter signature. As an example :
Code: CSharp
public class MyClass
{
public MyClass()
{
// This is the default constructor method.
}
public MyClass(int no)
{
// This is the constructor with one parameter.
}
public MyClass(int no, string Name)
{
// This is the constructor with two parameters.
}
}
Calling other constructors
You can call the other constructor like this :
Code: CSharp
public class MyClass
{
public MyClass(): this(10) // We are calling the one parameter constructor.
{
// This is the default constructor method.
}
public mySampleClass(int Age)
{
// This is the constructor with one parameter.
}
}
Now instead of calling the same class constructor you can also call the base class constructor using the
base keyword. Initialization List is not possible to have any variable name in C# as it was the case with C++ and we can only have this or base.