#293 – You Can Declare a Private Constructor

It’s possible to have one or more instance constructors be private.  A private constructor means that only code internal to the class can construct an instance using that particular combination of parameters.

Below is an example, where we have a public Dog constructor that takes two arguments, but a private one that takes only a name.

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

        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        private Dog(string name)
        {
            Name = name;
        }

A private constructor is typically called from within a static method in the class. For example:

        public static Dog MakeAnOldDog()
        {
            // Use private constructor
            Dog oldDog = new Dog("Rasputin");
            oldDog.Age = 15;

            return oldDog;
        }

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers