Constructors
Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments.
Types of Constructor
Copy Constructor
A constructor used for making objects by copying variables from other objects.
class Person
{
// Copy constructor.
public Person(Person previousPerson)
{
Name = previousPerson.Name;
Age = previousPerson.Age;
}
//// Alternate copy constructor calls the instance constructor.
//public Person(Person previousPerson)
// : this(previousPerson.Name, previousPerson.Age)
//{
//}
// Instance constructor.
public Person(string name, int age)
{
Name = name;
Age = age;
}
public int Age { get; set; }
public string Name { get; set; }
public string Details()
{
return Name + " is " + Age.ToString();
}
}
class TestPerson
{
static void Main()
{
// Create a Person object by using the instance constructor.
Person person1 = new Person("George", 40);
// Create another Person object, copying person1.
Person person2 = new Person(person1);
// Change each person's age.
person1.Age = 39;
person2.Age = 41;
// Change person2's name.
person2.Name = "Charles";
// Show details to verify that the name and age fields are distinct.
Console.WriteLine(person1.Details());
Console.WriteLine(person2.Details());
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
// Output:
// George is 39
// Charles is 41Instance/Parameterized Constructor
A constructor which have one or more parameters.
You declare an instance constructor to specify the code that is executed when you create a new instance of a type with the
newexpression.
Parameterless (Default) Constructor
If a class has no explicit instance constructors, C# provides a parameterless (default) constructor that you can use to instantiate an instance of that class.
Private Constructor
It is generally used in classes that contain static members only.
If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.
The declaration of the empty constructor prevents the automatic generation of a parameterless constructor.
Static Constructor
A static constructor is used to initialize any static data/fields, or to perform a particular action that needs to be performed only once.
It is called automatically before the first instance is created or any static members are referenced.
A class or struct can only have one static constructor.
Last updated
Was this helpful?