#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();
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: