A constructor is a method that is called when a new instance of a class is created. (Technically, this definition applies to instance constructors–I’ll cover static constructors later).
A constructor normally allows a class to initialize its data members, as part of the process of creating a new instance.
A constructor is defined by using the class’ name as the method name. The simplest form of constructor, known as thedefault constructor, takes no parameters.
1
2
3
4
5
6
7
8
9
10
11
12
| public class Dog{ public string Name { get; set; } public int Age { get; set; } // Constructor, called when we create a new Dog public Dog() { // Set a default name Name = "Pooch"; }} |
The constructor in the above example is called when we create a new instance of a Dog, using the new operator.
1
2
3
| Dog someDog = new Dog();Console.WriteLine(someDog.Name); // Pooch |

