#286 – A Constructor is Called When an Instance of a Class Is Created

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 the default constructor, takes no parameters.

    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.

            Dog someDog = new Dog();

            Console.WriteLine(someDog.Name);       // Pooch