#291 – No Default Constructor if You Define any Constructors

If you don’t define any constructors in a class, the compiler automatically generates a default parameterless constructor.  You can then create a new instance of the object without passing any parameters.

            Dog d1 = new Dog();

If you define at least one constructor, the compiler no longer generates a parameterless constructor.

Below, we define a single constructor for Dog, accepting a name parameter.

    public class Dog
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public Dog(string name)
        {
            Name = name;
            Age = 1;
        }
    }

Now we can define a new instance of Dog by passing in a name parameter.  But we can no longer create a new instance using no parameters.

            Dog d1 = new Dog("Rin Tin Tin");

            // Compiler error: Dog does not contain a constructor
            //   that takes 0 arguments.
            Dog d2 = new Dog();