#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;
        }
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.

2 Responses to #293 – You Can Declare a Private Constructor

  1. Pingback: #819 – A Private Constructor May Prevent Inheritance | 2,000 Things You Should Know About C#

  2. Pingback: #820 – A Protected Constructor Allows a Subclass to Create Instances | 2,000 Things You Should Know About C#

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: